【问题标题】:While parsing a file into an array, only the last element is initalised将文件解析为数组时,仅初始化最后一个元素
【发布时间】: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


【解决方案1】:

下面两行初始化数组应该只执行一次,而不是文件中的每一行/单词。

int length = Integer.parseInt(tokens[1]);
words = new String[length];

改成

while(reader.hasNextLine()){
    line = reader.nextLine();
     if (line.contains("Number of words")){
        tokens = line.split(",");
        int length = Integer.parseInt(tokens[1]);
        words = new String[length]; //Initialize the words array
        continue;
     }
      words[counter] = line;
      counter++;
     //Or a one liner -  words[counter++] = line;
}

【讨论】:

    【解决方案2】:

    在您的 while 循环中,您拥有

    words = new String[length];
    

    在每个循环迭代中创建一个新的String 数组

    所以你实际上将每一行分配给它自己的一个数组,并且只保留最后一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多