這一段簡單的代碼中使用時java.util.Scanner中的異常行爲:與System.in
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args){
Scanner sc1 = new Scanner(System.in);
int number1 = sc1.nextInt();
sc1.close();
Scanner sc2 = new Scanner(System.in);
int number2 = sc2.nextInt();
sc2.close();
}
}
總是給我這個錯誤:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at mainpkg.TestScanner.main(TestScanner.java:14)
這其中也不起作用。這次它陷入了一個永無止境的循環!
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args){
Scanner sc1 = new Scanner(System.in);
int number1 = sc1.nextInt();
sc1.close();
Scanner sc2 = new Scanner(System.in);
while(!sc2.hasNextInt())
;
int number2 = sc2.nextInt();
sc2.close();
}
}
爲什麼?
我希望有一個很好的理由可以對這個問題投下贊成票! – RGO