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?
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:
n
and m
n
linesBasically, 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();
...
See more on this question at Stackoverflow