java - 将整数打印到新行直到某个点
问题描述
假设我有一个文本文件:
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 循环,但似乎没有让它工作,而且数字不在不同的行上。我不明白为什么当我运行代码时条件不起作用并且打印时每一行都没有分开。我一直在努力寻找解决方案,并决定在这里提问。这可能是一个简单的问题,但我有一段时间没有编码了,所以请告诉我。提前致谢。
解决方案
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();
}
}
}
推荐阅读
- python - 如何使用 python selenium 识别这个按钮?
- mysql - 如何修复 Sql 查询
- python - AWS Lambda 和 S3:将 s3 对象路径传递给图像处理函数
- webpack - 无法创建中继容器;graphql.js 文件似乎有 webpack 工件?
- android - 将图像放置在卡片视图中时不会出现图像
- sql - MS Access 中可更新的完全外连接
- python - 如何在遵守列表顺序的同时将 pandas .replace() 与正则表达式列表一起使用?
- angular - 用于填充强类型变量的 Angular 方法
- go - Postgres 自动重新连接
- html - 如何使用 webpack 在静态 html 页面中导入静态资产?