spa*_*ron 16 java java.util.scanner
如何在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());
}
}
Run Code Online (Sandbox Code Playgroud)
这个问题是它没有读取最后一行.所以,如果我输入
10 5 4 20
11 6 55 3
9 33 27 16
Run Code Online (Sandbox Code Playgroud)
它的输出只会是
10 5 4 20 11 6 55 3
Run Code Online (Sandbox Code Playgroud)
Dan*_*ell 13
理想情况下,您应该添加最终的println(),因为默认情况下,System.out使用的PrintStream仅在发送换行符时刷新.请参阅何时/为何在Java中调用System.out.flush()
while (input.hasNext()) {
System.out.print(input.nextLine());
}
System.out.println();
Run Code Online (Sandbox Code Playgroud)
虽然您的问题可能还有其他原因.
小智 7
之前发布的建议存在拼写错误(hasNextLine 拼写)和新行打印(println 需要每行)问题。以下是更正后的版本——
import java.util.Scanner;
public class XXXX {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNextLine()){
System.out.println(input.nextLine());
}
}
}
Run Code Online (Sandbox Code Playgroud)