用txt填充int数组java

问题描述:

嗨,我想用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

是的,但不是你在这里做什么。因此,导致错误的代码与您发布的代码不同。 –

既具有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++; 
    } 
}