Read input line by line

不羁岁月 提交于 2019-12-21 07:06:10

问题


How do I read input line by line in Java? I searched and so far I have this:

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());
        }
    }

The problem with this is that it doesn't read the last line. So if I input

 10 5 4 20
 11 6 55 3
 9 33 27 16

its output will only be

10 5 4 20 11 6 55 3

回答1:


Ideally you should add a final println() because by default System.out uses a PrintStream that only flushes when a newline is sent. See When/why to call System.out.flush() in Java

while (input.hasNext()) {
    System.out.print(input.nextLine());
}
System.out.println();

Although there are possible other reasons for your issue.




回答2:


The previously posted suggestions have typo (hasNextLine spelling) and new line printing (println needed each line) issues. Below is the corrected version --

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());
        }
    }
}



回答3:


Try using hasnextLine() method.

while (input.hasnextLine()){


    System.out.print(input.nextLine());


 }


来源:https://stackoverflow.com/questions/11842091/read-input-line-by-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!