【发布时间】:2018-03-25 09:06:01
【问题描述】:
我正在尝试从一个文件(我自己写的)中取出一组单词。文件的第一行告诉我数组应该有多长,但由于某种原因,只有最后一个元素被初始化。我是初学者,所以我确定这是一个简单的解决方法,但我似乎无法弄清楚...
public class WordReader {
String[] words;
public WordReader() {
String line;
String[] tokens = new String[2];
int counter = 0;
try{
File infile = new File("resources/FunnyWords.txt");
Scanner reader = new Scanner(infile);
while(reader.hasNextLine()){
line = reader.nextLine();
if (line.contains("Number of words")){
tokens = line.split(",");
continue;
}
int length = Integer.parseInt(tokens[1]);
words = new String[length];
words[counter] = line;
counter++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
如果您能提供帮助,我将不胜感激.. 谢谢!
【问题讨论】:
-
文件的内容看起来像...?
-
continue 的意思是“下一行”,你确定需要那个吗?
-
在循环的每次迭代中,您重新创建
words数组...可能应该在if语句中完成
标签: java arrays file parsing element