下面是從布魯斯·埃克爾在Java編程思想爲例,第4版如何處理InputMismatchException?
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。如何解決這個問題呢?
感謝名單,該工作 – 2012-02-12 13:11:17