2014-05-03 67 views
1

我有這種方法,並從控制檯(鍵盤)讀取一個int數字序列的想法,並將它們全部添加到ArrayList中,即時使用類Scanner讀取數字,但在for循環不起作用,它會拋出「java.util.NoSuchElementException」。從控制檯讀取循環中的掃描儀

public static int mayorNumberSecuence(){ 
     System.out.println("Give me a size "); 
     Scanner sn = new Scanner(System.in); 
     int n = sn.nextInt(); 
     sn.close(); 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     for (int i=0; i<= n; ++i){ 
      System.out.println("Give me a number "); 
      Scanner sn2 = new Scanner(System.in); 
      int in = sn2.nextInt(); 
      list.add(in); 
      sn2.close(); 
     } 

回答

0

首先,使用一臺掃描儀,而不是每次重新創建掃描儀。另外,for循環會循環一次。

Scanner sn = new Scanner(System.in); 
System.out.println("Give me a size "); 
int n = sn.nextInt(); 
ArrayList<Integer> list = new ArrayList<Integer>(); 
for (int i = 0; i < n; i++){ 
    System.out.println("Give me a number "); 
    int in = sn.nextInt(); 
    list.add(in); 
} 
sn.close(); 

這對我來說很好,最後列表包含我輸入的所有數字。

您可以通過打印列表測試:

System.out.println(list); 

與您的舊代碼的問題是,當你在掃描儀使用.close(),它關閉底層InputStream,這是System.in。如果關閉System.in,則不能在下一臺掃描儀中再次使用它。這就是使用一臺掃描儀修復問題的原因。

+1

這隻給出答案的一半。 –

4

你的問題是在這裏:

Scanner sn = new Scanner(System.in); 
int n = sn.nextInt(); 
sn.close(); 

你關閉當前Scanner,這將關閉用於讀取數據的InputStream,這意味着你的應用程序將不會接受來自用戶的任何更多的投入。這就是爲什麼創建一個新的Scanner將從System.in讀取將無法正常工作。即使您使用System.in創建另一種閱讀器也不行。

通常情況下,與System.in打交道時,你創建一個單一讀者(在這種情況下,Scanner),將所有的應用程序。所以,你的代碼應該是這樣的:

System.out.println("Give me a size "); 
Scanner sn = new Scanner(System.in); 
int n = sn.nextInt(); 
//sn.close(); 
List<Integer> list = new ArrayList<Integer>(); 
for (int i=0; i < n; ++i){ 
    System.out.println("Give me a number "); 
    //Scanner sn2 = new Scanner(System.in); 
    int in = sn.nextInt(); 
    list.add(in); 
    //sn2.close(); 
}