简体   繁体   English

InputMismatchException读取十进制数字

[英]InputMismatchException reading a decimal number

I get the following error when entering 55.5 as answer to the first prompt. 输入55.5作为对第一个提示的答案时,出现以下错误。 I don't get the error when entering 50 . 输入50时我没有得到错误。

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at Miles.main(Miles.java:9)
Java Result: 1
import java.util.Scanner;

public class Miles {
    public static void main(String[] args){ 
        Scanner input = new Scanner(System.in); 
        System.out.println ("Enter the amount of water in kilograms");
        double m = input.nextDouble();

        System.out.println ("Enter the initial temprature");
        double initialTempreture = input.nextDouble();

        System.out.println ("Enter the final termprature");
        double finalTemprature = input.nextDouble();

        double q = m * (initialTempreture - finalTemprature) * 4184;

        System.out.print (q);
    }
}

You are living in a country where the decimal separator is not . 您生活在没有十进制分隔符的国家. .

You should change the locale with Scanner.useLocale(locale) : 您应该使用Scanner.useLocale(locale)更改语言Scanner.useLocale(locale)

input.useLocale(Locale.ENGLISH);

This way, Java will recognize . 这样,Java就会识别. as the decimal separator. 作为小数点分隔符。

If you want to know the decimal separator you are using in your default locale, you can use: 如果您想知道在默认语言环境中使用的小数点分隔符,可以使用:

System.out.println(DecimalFormatSymbols.getInstance().getDecimalSeparator());

Oh thanks! 哦谢谢! I just found out that it does indeed work with a , as seperator. 我刚刚发现它确实可以和分隔符一起使用。 Ill keep this in mind :) 我会牢记这一点:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM