2016-02-17 67 views
0

我試圖從一個.txt文件讀取整數,並且在輸入後直接得到這個錯誤,即使while循環包含hasNextInt以確保文件中有另一個整數要讀取。嘗試從文件讀取整數時發生NoSuchElementException?

import java.util.Scanner; 
import java.io.*; 

public class Part2 { 

    public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 

    String prompt = ("Please input the name of the file to be opened: "); 
    System.out.print(prompt); 
    String fileName = input.nextLine(); 
    input.close(); 
    Scanner reader = null; 

    try{ 
     reader = new Scanner(new File(fileName)); 
    } 

    catch(FileNotFoundException e){ 
     System.out.println("--- File Not Found! Exit program! ---"); 
    } 

    int num = 0; 
    while(reader.hasNextInt()){ 
     reader.nextInt(); 
     num++; 
    } 

    int[] list = new int[num]; 
    for(int i = 0; i<num; i++){ 
     list[i] = reader.nextInt(); 
    } 

    reader.close(); 

    System.out.println("The list size is: " + num); 
    System.out.println("The list is:"); 
    print(list);//Method to print out 
    }//main 
}//Part2 
+0

1.'打印(列表);'??似乎失去了,那裏肯定缺少一些東西。 – nullpointer

+0

對不起,這是稍後在代碼中的方法 – ConfusedStudent

回答

1

這是因爲在while循環中,您已到達文件的末尾。

while(reader.hasNextInt()){ 
      reader.nextInt(); 
      num++; 
     } 

嘗試在while循環後重新初始化它。

reader = new Scanner(new File(fileName)); 
0

我認爲這是更好地使用List

List list = new ArrayList(); 
int num = 0; 
while(reader.hasNextInt()){ 
    list.add(reader.nextInt()); 
    num++; 
} 

/* this part is unnecessary 
int[] list = new int[num]; 
for(int i = 0; i<num; i++){ 
    list[i] = reader.nextInt(); 
} 
*/ 
//then 
System.out.print(list); 
+0

List list = new ArrayList();可以更改爲列表 list = new ArrayList (); –

相關問題