【问题标题】:Scanner sc - Output number to 2 decimal places [duplicate]扫描仪 sc - 输出数字到小数点后 2 位 [重复]
【发布时间】:2015-09-09 15:11:56
【问题描述】:

我是 JAVA 和一般编程的新手。所以请耐心等待。我试图以 2 位小数输出 PI,但是当我输入 3.14 时,我得到一个

Exception in thread "main" java.util.InputMismatchException

我觉得我已经很接近了,我只需要稍微调整代码就可以了。我已经扫描了几天的论坛,但似乎无法使其正常工作。任何解释/帮助将不胜感激!

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  System.out.println("What is the value of PI to two decimal places? : ");
  int pi = sc.nextInt();
  System.out.println("PI is: " + pi);
}

【问题讨论】:

    标签: java integer java.util.scanner pi


    【解决方案1】:

    你应该扫描一个双精度数,而不是一个整数。您应该将其格式化为两位得到 2 位小数。

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println( "What is the value of PI to two decimal places?:");
        double pi = sc.nextDouble();
        DecimalFormat df = new DecimalFormat("#.00");
        String piStr = df.format( pi);
        System.out.println("PI is: " + piStr);
    }
    

    【讨论】:

    • 太棒了!谢谢!
    【解决方案2】:

    “3.14”不是整数,所以当你到达时

    int pi = sc.nextInt();
    

    你加注

    Exception in thread "main" java.util.InputMismatchException
    

    您应该更改代码并尝试:

    Scanner sc = new Scanner(System.in);
        System.out.println("What is the value of PI to two decimal places? : ");
        double pi = sc.nextDouble();
        System.out.println("PI is: " + pi);
        }
    

    结果:

    What is the value of PI to two decimal places? : 
    3,14
    PI is: 3.14
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 2016-06-20
      • 2015-09-06
      • 1970-01-01
      • 2018-05-30
      相关资源
      最近更新 更多