Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read input line by line

Tags:

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
like image 406
spacitron Avatar asked Aug 07 '12 08:08

spacitron


1 Answers

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.

like image 160
Dan Gravell Avatar answered Oct 01 '22 10:10

Dan Gravell