【发布时间】:2020-07-30 23:50:21
【问题描述】:
我有一个简单的问题。我尝试读取文件,我想将每个单词添加到我的数组“短语”中。问题出现在 for 循环中。我得到了异常“索引 0 超出长度 0 的范围”。 你能帮我吗?
String [] tokens;
String line;
String hash = " ";
int n = 0;
String [] phrase = new String [n];
public void loadFile()
{
try
{
@SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader("z3data1.txt"));
while((line = br.readLine()) != null)
{
tokens = line.split("[ ]");
n += tokens.length;
}
for(int j = 0; j<tokens.length; j++)
{
phrase[j] = tokens[j];
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
【问题讨论】:
-
您将 n 设置为 0,因此短语的长度也为 0。如果您想要可变长度的内容,请使用 ArrayList。
-
好的,谢谢。但是在while循环中增加n是错误的吗?
-
不,虽然我不明白它的意义
标签: java arrays string file exception