18

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
Tim
  • 33,823
  • 10
  • 86
  • 115
spacitron
  • 379
  • 1
  • 2
  • 14

3 Answers3

16

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.

Community
  • 1
  • 1
Dan Gravell
  • 7,049
  • 4
  • 36
  • 55
  • 1
    how the hell does this answer answer the question?? – Bohdan Jan 16 '18 at 17:55
  • @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 – Adam Burley Jan 26 '21 at 09:53
3

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());
        }
    }
}
Robert Field
  • 419
  • 3
  • 5
1

Try using hasnextLine() method.

while (input.hasnextLine()){


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


 }
Kumar Vivek Mitra
  • 32,278
  • 6
  • 43
  • 74