不将单词保存在数组中 [英] Doesn't save the words in array
问题描述
我有一个可能很简单的问题。我尝试读取文件,并且想将每个单词添加到数组短语中。问题发生在for循环中。我得到了异常索引0超出长度0的界限。
您能帮我吗?
i've got a propably simple question. I try to read the file and i want to add each single word to my array "phrase". The problem occures in for loop. I got the exception "index 0 out of bounds for length 0". Can you please help me with that?
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();
}
}
推荐答案
A
- 由于数组不够大且索引
j而出现错误
超出了大小。 - 您一直在
while循环
中覆盖令牌。 while循环需要包含将令牌复制到短语数组。
- you are getting the error because your array is not large
enough and the indexj
is exceeding its size. - you keep overwriting tokens in the
while loop
. The while loop needs to encompass the copying of the tokens to the phrase array.
因此,请尝试以下操作:
So try the following:
while((line = br.readLine()) != null) {
tokens = line.split("[ ]");
n += tokens.length; // don't really need this.
//starting offset to write into phrase
int len = phrase.length;
phrase = Arrays.copyOf(phrase,phrase.length + tokens.length);
for(int j = 0; j<tokens.length; j++) {
phrase[j + len] = tokens[j];
}
}
此语句
phrase = Arrays.copyOf(phrase,phrase.length + tokens.length)
复制短语的内容并增加数组大小以处理令牌的编写。
Copies the contents of phrase and increases the array size to handle the writing of tokens.
另一种(可能是首选的)替代方法是使用 List< String>
随需要而增长。
Another (and probably preferred) alternative is to use a List<String>
which grows as you need it.
List<String> phrase = new ArrayList<>();
for(int j = 0; j<tokens.length; j++) {
phrase.add(tokens[j]);
}
// or skip the loop and just do
Collections.addAll(phrase,tokens);
一个观察。我不知道您要拆分的内容,但您的拆分语句看起来可疑。
One observation. I don't know what you are splitting on but your split statement looks suspicious.
这篇关于不将单词保存在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!