2017-10-04 67 views
-3

嗨,我想用txt文件中的值填充數組,但運行程序時出現錯誤java.util.NoSuchElementException: No line found,這是我的代碼。用txt填充int數組java

private static void leeArchivo() 
{ 
    Scanner s = new Scanner(System.in); 
    //Size of the array 
    int size = Integer.parseInt(s.nextLine()); 
    datos = new int[size]; 
    while (s.hasNextLine()) { 
     for (int i = 0; i < size; i++) { 
      //fill array with values 
      datos[i] = Integer.parseInt(s.nextLine()); 
     } 
    } 
} 

的TXT應該是這樣的,第一行是數組的大小:

4 

75 

62 

32 

55 
+2

但在這裏你沒有讀取文件。您正在閱讀用戶輸入。 –

+0

據我所知,你可以使用掃描儀輸入一個txt文件,不僅僅是緩衝讀寫器 –

+1

是的,但不是你在這裏做什麼。因此,導致錯誤的代碼與您發佈的代碼不同。 –

回答

1

既具有while環路和環路for似乎是你的問題的原因。如果你確定你的輸入是正確的,即。行數相匹配的第一個數字,那麼你可以做這樣的事情:

private static void leeArchivo() 
{ 
    Scanner s = new Scanner(System.in); 

    //Size of the array 
    int size = Integer.parseInt(s.nextLine()); 
    datos = new int[size]; 

    for (int i = 0; i < size; i++) { 
     //fill array with values 
     datos[i] = Integer.parseInt(s.nextLine()); 
    } 
} 

在上面的代碼,沒有測試hasNextLine(),因爲它不是必需的,因爲我們知道存在下一行。如果你想玩它安全,使用這樣的事情:

private static void leeArchivo() 
{ 
    Scanner s = new Scanner(System.in); 

    //Size of the array 
    int size = Integer.parseInt(s.nextLine()); 
    datos = new int[size]; 

    int i = 0; 
    while ((i < size) && s.hasNextLine()) { 
     //fill array with values 
     datos[i] = Integer.parseInt(s.nextLine()); 
     i++; 
    } 
}