我不明白为什么这段代码会像我期望的那样工作:
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是:
weight = scan2.nextDouble();
我很感激任何人对这种行为的见解!