Getting problems reading a number of lines with a scanner
I am trying to read the input which is in the following format.
2 asdf asdf 3 asd df 2
Below is the code:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
System.out.println(t);
while(t>0){
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
}
But when I scan, I get a blank t=2
, a=""
, b=asdf
,K=asdf
Can't figure out the problem. No space / newline between 2 and asdf.
I tried using scanner.nextLine()
instead scanner.next()
, but no change
source to share
nextInt()
does not require the use of a newline token, so the next read will get it. You can type nextLine
after nextInt
to skip it:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
System.out.println(t);
while(t > 0) {
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
}
source to share
Another approach that I prefer:
Scanner scanner = new Scanner(System.in);
int t = Integer.parseInt(scanner.nextLine());
System.out.println(t);
while(t>0){
String a = scanner.nextLine();
String b = scanner.nextLine();
int K = Integer.parseInt(scanner.nextLine());
}
But note that this will throw a NumberFormatException if the input is incorrect.
source to share