“线程中的exception”main“java.util.InputMismatchException”**

我已经搜索了但我似乎无法在代码中找到任何错误,请帮忙!

代码编译但是,当我想回答问题3时,这是我得到的错误:

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextDouble(Unknown Source) at ForgetfulMachine.main(ForgetfulMachine.java:16) 

这是我的代码:

 import java.util.Scanner; public class ForgetfulMachine { public static void main( String[] args ) { Scanner keyboard = new Scanner(System.in); System.out.println( "What city is the capital of Germany?" ); keyboard.next(); System.out.println( "What is 6 divided by 2?" ); keyboard.nextInt(); System.out.println( "What is your favorite number between 0.0 and 1.0?" ); keyboard.nextDouble(); System.out.println( "Is there anything else you would like to tell me?" ); keyboard.next(); } } 

如果条目的格式对于扫描程序的区域设置不正确,则扫描Scanner将抛出此exception。 特别是,在您的情况下,如果使用错误的小数分隔符。 两者. 并且,是常见的特定于语言环境的小数分隔符。

要找出您的默认语言环境的小数分隔符,您可以使用:

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

也可以看看:

  • Scanner#locale()
  • Scanner#useLocale(Locale)
  • DecimalFormatSymbols#getInstance(Locale)

您的代码没有任何问题。 输入数据时尊重类型。 当你期望一个整数等时,不要输入一个双精度。你可以通过应用防御性编码来解决这种类型的错误,你只接受用户符合预期值的数据。

 public static void main(String[] arg) { Scanner keyboard = new Scanner(System.in); System.out.println( "What city is the capital of Germany?" ); keyboard.nextLine(); System.out.println( "What is 6 divided by 2?" ); boolean isNotCorrect = true; while(isNotCorrect){ isNotCorrect = true; try { Integer.valueOf(keyboard.nextLine()); isNotCorrect = false; } catch (NumberFormatException nfe) { System.out.println( "Enter an integer value" ); } } System.out.println( "What is your favorite number between 0.0 and 1.0?" ); isNotCorrect = true; while(isNotCorrect){ try { Double.valueOf(keyboard.nextLine()); isNotCorrect = false; } catch (NumberFormatException nfe) { System.out.println( "Enter a double value" ); } } System.out.println( "Is there anything else you would like to tell me?" ); keyboard.next(); }