简体   繁体   English

使用扫描仪读取一系列行时出现问题

[英]Getting issues while reading series of lines using scanner

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=2a=""b=asdfK=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()但没有改变

nextInt() doesn't cosume the newline token, so the following read will get it. nextInt()不会使用换行符号,因此以下读取将获取它。 You could introduce a nextLine after the nextInt to skip it: 您可以在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
}

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM