java – nextDouble()在输入double时抛出异常

前端之家收集整理的这篇文章主要介绍了java – nextDouble()在输入double时抛出异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import java.util.*;

class Averager
{
    public static double unlimited()
    {
        int count = 0;
        double sum = 0;
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext())
        {
            double d = scan.nextDouble();
            sum += d;
            count++;
        }
        double ave = sum/count;
        return ave;
    }

    public static void main(String[] args) {
        System.out.println(unlimited()+"\n");
    }
}

使用整数时没有错误,但如果我使用带有点的数字则会出现错误.

$javac Averager.java; java Averager
0.5
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextDouble(Scanner.java:2387)
    at Averager.unlimited(Averager.java:12)
    at Averager.main(Averager.java:21)

据我所知,0.5应该用双倍覆盖.如果不是,请有人纠正我.

@R_502_323@

它可能依赖于语言环境.在瑞典,十进制数字例如写为0.5.

改变你的代码,以便例如:

Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.US);
原文链接:https://www.f2er.com/java/127659.html

猜你在找的Java相关文章