25

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
4
  • 5
    Works fine for me using your exact code. Don't forget to press enter.
    – FThompson
    Aug 7, 2012 at 8:37
  • Why not Scanner.hasNextLine?
    – obataku
    Aug 7, 2012 at 8:38
  • I think you have copied than pasted all input variable at once Aug 7, 2012 at 8:40
  • 2
    Lol, I did't press enter. I feel dumb now.
    – spacitron
    Aug 7, 2012 at 8:42

3 Answers 3

20

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
  • 1
    how the hell does this answer answer the question??
    – Bohdan
    Jan 16, 2018 at 17:55
  • 1
    @Bohdan the answer is in the comments under the question. The OP just forgot to press enter after the last line, so it was not processed by the program. I guess he just accepted the most-upvoted answer after he realised he was "dumb" (his words not mine) for not pressing enter Jan 26, 2021 at 9:53
7

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

Try using hasnextLine() method.

while (input.hasnextLine()){


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


 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.