nextDouble() 不接受点,只接受逗号 [duplicate]

nextDouble() don't accept points, just commas [duplicate]

提问人:KevinDoUrden 提问时间:10/24/2021 最后编辑:MureinikKevinDoUrden 更新时间:10/24/2021 访问量:394

问:

输入是这样的:

185.50
250.36
163.45
535.20
950.22
450.38
-1

它抛给我这个:

Exception in thread "main" java.util.InputMismatchException<br>
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)<br>
    at java.base/java.util.Scanner.next(Scanner.java:1594)<br>
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)<br>
    at Pruebas.Ventas.main(Ventas.java:25)

但是如果我输入这个:

185.50
250.36
163.45
535.20
950.22
450.38
-1

它完美地工作!为什么?

import java.util.Scanner;

public class Ventas {

    public static void main(String[] args) {


        Scanner scan = new Scanner(System.in);

        double numero = 0;
        double grande = 0;
        double pequeno = 0;
        double suma = 0;
        double media = 0;
        String comprobacion = "";
        int grandePos = 0;
        int pequenoPos = 0;
        String[] semana = {"Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"};

        while(numero != -1) {
            double[] dias = new double[6];
            for (int i = 0; i < dias.length; i++) {
                numero = scan.nextDouble(); // This is line 25!
                suma += numero;
                if(numero != -1) {
                    dias[i] = numero;
                    if(numero > grande) {
                        grande = numero;
                        grandePos = i;
                    }else if(pequeno == 0 || numero < pequeno) {
                        pequeno = numero;
                        pequenoPos = i;
                    }
                }else {
                    break;
                }
            }
            media = ((suma - dias[5]) / 5);
            if(media < dias[5]) {
                comprobacion = "NO";
            }else {
                comprobacion = "SI";
            }
        }
        
        System.out.println(semana[grandePos] + " " + semana[pequenoPos] + " " + comprobacion);

        scan.close();
    }

}
Java Eclipse 异常 java.util.scanner

评论


答:

2赞 Mureinik 10/24/2021 #1

默认区域设置使用逗号字符 () 作为小数分隔符,因此无法解析小数点 () 作为双精度的输入。您可以通过显式设置接受小数点来覆盖此行为。例如:,.Locale

Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.US);