如何处理InputMismatchException?

时间:2012-02-12 12:52:43

标签: java exception

以下是Bruce Eckel Thinking in Java,第4版

的一个例子
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.Scanner;

public class BetterRead {
  public static void main(String[] args) {
    BufferedReader input = new BufferedReader(new StringReader("Sir Robin of Camelot\n22 1.61803"));
    Scanner stdin = new Scanner(input);
    System.out.println("What is your name?");
    String name = stdin.nextLine();
    System.out.println(name);
    System.out.println("How old are you? What is your favorite double?");
    System.out.println("(input: <age> <double>)");
    int age = stdin.nextInt();
    double favorite = stdin.nextDouble();
    System.out.println(age);
    System.out.println(favorite);
    System.out.format("Hi %s.\n", name);
    System.out.format("In 5 years you will be %d.\n",
      age + 5);
    System.out.format("My favorite double is %f.",
      favorite / 2);
  }
}

这是输出

 What is your name?
Sir Robin of Camelot
How old are you? What is your favorite double?
(input: <age> <double>)
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextFloat(Scanner.java:2388)
    at betterread.BetterRead.main(BetterRead.java:21)
Java Result: 1

我对Java很新,但正如你在本例中所见,int跟随买双。所以它可能正常工作。但仍抛出InputMismatchException。如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

问题似乎是你的Locale,因为1.61803似乎不是它的有效双倍。试试1,61803。

答案 1 :(得分:0)

我认为行问题可能与Scanner stdin = new Scanner(input);有关,请在此处尝试:Scanner stdin = new Scanner(System.in);