【问题标题】:Trying to output double with no decimal when double is entered as an int当 double 作为 int 输入时,尝试输出不带小数的 double
【发布时间】:2019-03-17 20:46:42
【问题描述】:

每当为我的双精度输入一个 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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我可以建议在输入字符串中点检查

    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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      相关资源
      最近更新 更多