如何在 Java 中逐行读取输入?我搜索过,到目前为止我有这个:
import java.util.Scanner;
public class MatrixReader {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
System.out.print(input.nextLine());
}
}
问题是它没有读取最后一行。所以如果我输入
10 5 4 20
11 6 55 3
9 33 27 16
它的输出只会是
10 5 4 20 11 6 55 3
最佳答案
理想情况下,您应该添加一个最终的 println(),因为默认情况下 System.out 使用仅在发送换行符时才刷新的 PrintStream。参见 When/why to call System.out.flush() in Java
while (input.hasNext()) {
System.out.print(input.nextLine());
}
System.out.println();
尽管您的问题可能还有其他原因。
关于java - 逐行读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11842091/