将整数打印到新行,直到某一点



假设我有一个包含以下内容的文本文件:

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循环,但似乎无法实现,而且数字不在不同的行上。我不明白为什么当我运行代码时,条件不起作用,并且打印时每行都没有分开。一段时间以来,我一直在努力寻找解决方案,并决定在这里提问。这可能是一个简单的问题,但我已经有一段时间没有编码了,所以请告诉我。提前谢谢。

while中的reader.nextInt()将消耗下一个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();
}
}
}

试试这个。

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

我参加聚会迟到了。。。但只要别人在你接受后回复,我想我会分享我开始写的回复。。。但在你收到另外两个(很棒!(回复之前,回复太慢了。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Prac {
static final int EOL = -999;
public static void main(String[] args) throws FileNotFoundException {
File f = new File("test.txt");
try (Scanner reader = new Scanner(f)) {
int nextInt;
while(reader.hasNext()) {
if ((nextInt = reader.nextInt()) == EOL)
System.out.println();
else
System.out.print(nextInt + " ");
}
}
}
}

注意事项:1.主要问题是您没有在while循环中捕获"scanner.nextInt(("的值。因此,您跳过了其他所有值。

  1. 还有一个资源泄漏-您没有关闭扫描仪。对于这样的小程序来说,这并不重要(退出程序会很好地关闭文件;(。

    一种方法是执行显式的"close(("。

    如上所示,另一种选择是在Java8中引入的try-with-resources语句。

问题是您没有将reader.nextInt()的值保存在while循环中。你可以试试这个:

while (reader.hasNextLine()) {
int nextInt = reader.nextInt();
System.out.print( nextInt != -999 ? nextInt + " " : "n");
}

相关内容

最新更新