【发布时间】:2014-09-18 03:51:42
【问题描述】:
我在 while 循环中不断收到此错误:java.lang.ArrayIndexOutOfBoundsException; 这是在:将新数据从“Input.txt”中读取到名称数组中,每行一个字符串,并将它们放在一个数组中。文件中字符串的数量必须与数组中的单元格数量相同。
// Open an input textfile named "Input.txt".
File f = new File("Input.txt");
Scanner inputFile = new Scanner(f);
System.out.println("\nThe array contents:");
// Read new data into the array of names from "Input.txt" one String per line, and places them in an array.
//The number of Strings in the file must be the same as the number of cells in the array.
String[] input = new String [5];
int k=0;
while (inputFile.hasNext())
{
String str = inputFile.nextLine();
input[k]=str;
k++;
}
inputFile.close();
//Print the new array contents on the screen
PrintWriter pw = new PrintWriter("Input.txt");
for(String str : array)
pw.println(str);
pw.close();
}
/**
* Method printOnScreen sends the entire contents of an
* array to the Screen using an "enhanced for" loop.
*
* @param array the array of Strings be printed on Screen
*
*/
public static void printOnScreen(String[] args)
{
for(String val : args)
System.out.println(val);
}
【问题讨论】:
-
尝试将这些行放在“ArrayList”中,然后在“ArrayList”上使用“toArray()”方法。
标签: java arrays eclipse compiler-errors