我正在尝试读取以下格式的输入。
2
asdf
asdf
3
asd
df
2
代码如下:
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();
}
但是当我扫描时,我得到的是空的 t=2
, a=""
, b=asdf
, K=asdf
无法解决问题。 2 和 asdf 之间没有空格/换行。
我试过使用 scanner.nextLine()
而不是 scanner.next()
但没有改变
最佳答案
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
}
关于java - 使用扫描仪读取一系列行时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30117981/