1. 程式人生 > >異常:java.util.NoSuchElementException

異常:java.util.NoSuchElementException

            Scanner sc = new Scanner(System.in).useDelimiter("\\s");
		int a[] = new int[50];
		int i = 0;
		while (sc.hasNextInt()) {
			a[i++] = sc.nextInt();
		}
		sc.close();
		Scanner sc2 = new Scanner(System.in);
		System.out.println("請輸入一個小於" + i + "的數");
		int m = sc2.nextInt();
		sc2.close();

上面這麼寫就會報java.util.NoSuchElementException異常:

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.nextInt(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)

原因是我們在上面關了System關閉,即對於系統檔案關閉了無法再開啟,所以就報錯了。改的方法很簡單,兩個Scanner放到最後一塊關閉就是了:

            Scanner sc = new Scanner(System.in).useDelimiter("\\s");
		int a[] = new int[50];
		int i = 0;
		while (sc.hasNextInt()) {
			a[i++] = sc.nextInt();
		}
		Scanner sc2 = new Scanner(System.in);
		System.out.println("請輸入一個小於" + i + "的數");
		int m = sc2.nextInt();
		sc.close();
		sc2.close();

這樣該報錯就解決了!


注:以上文章僅是個人學習過程總結,若有不當之處,望不吝賜教。