首页 > 解决方案 > 将整数打印到新行直到某个点

问题描述

假设我有一个文本文件:

2 4 6 7 -999
9 9 9 9 -999

当我运行程序时,我应该在每一行打印出除“-999”之外的所有内容。我应该得到的是:

 2 4 6 7 
 9 9 9 9 

这是我尝试过的:

public class Prac {
public static void main(String[] args) throws FileNotFoundException {

    Scanner reader = new Scanner(new File("test.txt"));
    while(reader.hasNextLine() && reader.nextInt() != -999) {
        int nextInt = reader.nextInt();
        System.out.print(nextInt + " ");
    }

}

}

我试过使用 while/for 循环,但似乎没有让它工作,而且数字不在不同的行上。我不明白为什么当我运行代码时条件不起作用并且打印时每一行都没有分开。我一直在努力寻找解决方案,并决定在这里提问。这可能是一个简单的问题,但我有一段时间没有编码了,所以请告诉我。提前致谢。

标签: java

解决方案


reader.nextInt()in将while消耗下一个 int,因此您将始终跳过一个整数。所以我建议:

    public static void main(String[] args) throws FileNotFoundException {
        Scanner reader = new Scanner(new File("test.txt"));
        while (reader.hasNextLine()) {
            int nextInt = reader.nextInt();
            if (nextInt != -999)
                System.out.print(nextInt + " ");
            else
                System.out.println();
        }
    }

更新:如果您想按照评论中的要求计算每行的平均值,您可以存储每个值以进行计算(请参阅此处的其他方式)。下面的代码将执行此操作并在行尾打印平均值:

    public static void main(String[] args) throws FileNotFoundException {
        Scanner reader = new Scanner(new File("test.txt"));
        List<Integer> values = new ArrayList<>();
        while (reader.hasNextLine()) {
            int nextInt = reader.nextInt();
            if (nextInt != -999) {
                System.out.print(nextInt + " ");
                values.add(nextInt);
            } else {
                int sum = 0;
                for (int value : values) {
                    sum += value;
                }
                System.out.println((float) sum / values.size());
                values.clear();
            }
        }
    }

推荐阅读