当double作为int输入时,尝试输出double而没有小数

问题描述 投票:-1回答:2

每当为我的double输入一个int时,我都会尝试打印出一个int。例如用户输入123456,输出123456;用户输入1.0,输出1.0。截至目前,我的代码无论如何打印出双倍。这是我的fullCellText方法。

我的代码:

package textExcel;

public class ValueCell extends RealCell {
    private boolean isInt;
    public ValueCell(String cell) { 
        super(cell);
        // TODO Auto-generated constructor stub
    }
    public ValueCell(String cell, boolean isInt) { 
        super(cell);
        this.isInt = isInt;
        // TODO Auto-generated constructor stub
    }
    public String fullCellText() {
        return "" + cell;
    }

}
java int double
2个回答
0
投票

不确定我是否正确理解了您的问题,但我认为您正在尝试打印没有小数值的双精度数。

您可以通过执行以下操作将double值转换为int值:int x = (int) y此处y为double。现在,如果您打印x,那么您将不会得到任何小数位。

注意:int类型转换不是一个好主意,因为你的双倍可能会超出范围。


0
投票

我建议点检查输入字符串

if (yourString.contains("."))

它不是解决这个问题的最佳方法,但它确实有效。

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String buff = scanner.nextLine();
        if (buff.contains(".")){
            double tempDouble = Double.parseDouble(buff);
            System.out.println(tempDouble);
        } else {
            int integer = Integer.parseInt(buff);
            System.out.println(integer);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.