John Doe
John Doe

Reputation: 2924

Why java Scanner is not reading all the lines?

Here is my code which just reads the lines from input stream and displays them but to my surprise its not reading all the lines. Its reading only upto second last line.

Here is my code :-

import java.util.*;

public class Solution {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    short n = scan.nextShort();
    short m = scan.nextShort();
    byte[][] topics = new byte[n][m];
    for(short i = 0; i < n; i++){
        char[] arr = scan.nextLine().toCharArray();
        display(arr);

    }
}

private static void display(char[] arr){
    for(int i = 0; i < arr.length; i++){
        System.out.print(arr[i]);
    }
    System.out.println();
  }
 }

The input is given in this format

  4 5
 10101
 11100
 11010
 00101

My output is this :-

 10101
 11100
 11010

Its not having the third line. Why?

Upvotes: 3

Views: 4330

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500105

The problem is that the first call to nextLine() is reading the empty "line" between the end of "5" (read for m) and the line break.

Personally, I would either stop using Scanner entirely (in favour of BufferedReader) - there's a huge number of questions a bit like this, with it not behaving exactly as you'd like - or only just nextLine(). Either way, basically process a line at a time:

  • Read the first line
  • Split it on space and parse the two substrings as n and m
  • Read the next n lines

Basically, Scanner is "token-oriented" whereas your input format is more "line-oriented".

If you do want to use Scanner.nextShort() you could always read the first line (either with a BufferedReader or a Scanner) and create a new scanner just from that string:

String firstLine = ...;
Scanner firstLineScanner = new Scanner(firstLine);
short n = firstLineScanner.nextShort();
short m = firstLineScanner.nextShort();
...

Upvotes: 1

Eran
Eran

Reputation: 393781

Add a scan.nextLine() before your for loop, to read the end of the first line (that contains "4 5"). Without it, the first call to scan.nextLine() inside the loop returns an empty String.

Upvotes: 2

Related Questions