首页 > 解决方案 > 为什么我的程序没有读取文本文件中的第一个整数?

问题描述

我已经完成了方法,它找到了带有成绩的 txt 文件,读取它们,然后将它们放入一个数组中,然后输出我们需要的指定值。出于某种原因,它没有采用所有整数。例如,如果我输入:

6、87、23、90

它只会读取最后三个。

87、23 和 90

//reads the data from the file
private static int[] readExamScores(String  userFile) throws FileNotFoundException{
    File inputFile = new File(userFile);
    Scanner stats = new Scanner(inputFile);

    try{
        int scores[] = new int[stats.nextInt()];
        int i = 0;
        while (stats.hasNext()){
            scores[i] = stats.nextInt();
            i++;
        }
        System.out.println("\n" + "There are " + (i) + " scores. \n");
        Arrays.sort(scores);
        return scores;
    }
    finally {
        stats.close();
    }
}

标签: javatext-files

解决方案


因为您的索引由于 init 和同时递增而已经移动了 1,例如 stats.nextInt()

我建议将 arraylist 修复为扫描仪“使用”如果您计算字符串行中的令牌或读取它返回的内容。

List<Integer> scores = new ArrayList<Integer>()
       int i = 0;
        while (stats.hasNext()){
            scores.add(stats.nextInt());
            i++;
        }

推荐阅读