I'm trying to read the input which is in the following format.
我正在尝试读取以下格式的输入。
2
asdf
asdf
3
asd
df
2
Following 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'm scanning, I'm getting empty t=2
, a=""
, b=asdf
, K=asdf
但是当我正在扫描时,我变空了t = 2,a =“”,b = asdf,K = asdf
Can't figure out the issue. There is no space/new line between 2 and asdf.
无法弄清楚这个问题。 2和asdf之间没有空格/新行。
I have tried using scanner.nextLine()
instead of scanner.next()
but no change
我曾尝试使用scanner.nextLine()而不是scanner.next()但没有改变
2 个解决方案
#1
nextInt()
doesn't cosume the newline token, so the following read will get it. You could introduce a nextLine
after the nextInt
to skip it:
nextInt()不会使用换行符号,因此以下读取将获取它。您可以在nextInt之后引入nextLine以跳过它:
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
}
#2
Another approach 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 it will throw NumberFormatException when input is incorrect.
但请注意,当输入不正确时,它将抛出NumberFormatException。
#1
nextInt()
doesn't cosume the newline token, so the following read will get it. You could introduce a nextLine
after the nextInt
to skip it:
nextInt()不会使用换行符号,因此以下读取将获取它。您可以在nextInt之后引入nextLine以跳过它:
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
}
#2
Another approach 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 it will throw NumberFormatException when input is incorrect.
但请注意,当输入不正确时,它将抛出NumberFormatException。