我一直在为while循环得到这个错误:java.lang.ArrayIndexOutOfBoundsException; 这是:将新数据读入" Input.txt"的名称数组中。每行一个String,并将它们放在一个数组中。文件中的字符串数必须与数组中的单元格数相同。
// 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);
}
答案 0 :(得分:0)
你得到ArrayIndexOutOfBoundException
,这意味着你的文件有超过5行,而String数组的长度只有5,所以抛出了异常。
如果你想从文件'Input.txt'中读取5个名字,那么在k> 5
while (inputFile.hasNext())
{
if(k>5) break;
String str = inputFile.nextLine();
input[k]=str;
k++;
}
或者如果要读取整个文件,则需要使用在创建时未定义大小的数组,如动态数组:ArrayList
List<String> input = new ArrayList<String>();
while (inputFile.hasNext())
{
String str = inputFile.nextLine();
input.add(str);
}
答案 1 :(得分:0)
您的数组大小似乎很短。如果您不确定数组大小,我建议您使用ArrayList。
List<String> input = new ArrayList<String>();
int k=0;
while (inputFile.hasNext())
{
String str = inputFile.nextLine();
input.add(str);
}
inputFile.close();
答案 2 :(得分:0)
工作示例
public class Test2 {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new FileReader("d:\\myFile.txt"));
String str;
List<String> list = new ArrayList<String>();
while ((str = input.readLine()) != null) {
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
System.out.println("\nThe array contents:");
for (String val : stringArr)
System.out.println(val);
}
}
<强>输出强>
数组内容:
stack
overflow
is
good
文字文件输入 myFile.txt
stack
overflow
is
good