我不明白为什么这段代码能按我的预期工作:
package myPackage;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ScanTest {
public static void main(String[] args)
{
Scanner scan1, scan2;
double weight = 0.0;
scan1 = new Scanner(System.in);
System.out.print("Enter a rational: ");
try {
weight = scan1.nextDouble();
System.out.println("You entered " + weight);
}
catch(InputMismatchException ime) {
System.out.println("Invalid data.");
}
scan1.close();
/*scan2 = new Scanner(System.in);
System.out.print("Enter a rational: ");
try {
weight = scan2.nextDouble();
System.out.println("You entered " + weight);
}
catch(InputMismatchException ime) {
System.out.println("Invalid data.");
}
scan2.close();*/
}
}
这段代码失败了:
package myPackage;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ScanTest {
public static void main(String[] args)
{
Scanner scan1, scan2;
double weight = 0.0;
scan1 = new Scanner(System.in);
System.out.print("Enter a rational: ");
try {
weight = scan1.nextDouble();
System.out.println("You entered " + weight);
}
catch(InputMismatchException ime) {
System.out.println("Invalid data.");
}
scan1.close();
scan2 = new Scanner(System.in);
System.out.print("Enter a rational: ");
try {
weight = scan2.nextDouble();
System.out.println("You entered " + weight);
}
catch(InputMismatchException ime) {
System.out.println("Invalid data.");
}
scan2.close();
}
}
(请注意,这两个版本几乎相同。第二个版本中只有一个未注释的块。)
我从第二个版本得到的输出是:
Enter a rational: .97
You entered 0.97
Enter a rational: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at myPackage.ScanTest.main(ScanTest.java:28)
我不明白为什么 Scanner 对象在第一个块中等待输入,但在第二个块中抛出异常。我期望的行为是:
Enter a rational: .97
You entered 0.97
Enter a rational: .43
You entered 0.43
有问题的第 28 行是:
重量 = scan2.nextDouble();
我将不胜感激任何人对这种行为的洞察力!