Reputation: 49
I don't understand why this code works as I expect:
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();*/
}
}
and this code fails:
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();
}
}
(Note that the two versions are nearly identical. There is merely an uncommented block in the second.)
The output I get from the second version is:
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)
I don't understand why the Scanner object waits for input in the first block, but throws an Exception in the second. The behavior I would expect is:
Enter a rational: .97
You entered 0.97
Enter a rational: .43
You entered 0.43
The offending line 28 is:
weight = scan2.nextDouble();
I would appreciate anyone's insight into this behavior!
Upvotes: 0
Views: 811