我正在运行这段代码以获得3个值:一个整数、一个字符串和一个来自用户的布尔,并将其打印成单独的行。
import java.util.*;
public class Practice {
public static void main(String[] args){
int a;
String b;
boolean c;
Scanner scanner = new Scanner(System.in);
a = scanner.nextInt();
b = scanner.nextLine();
c = scanner.nextBoolean();
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}我试图提供这样的投入:
1
hello world
true在写入第二行输入后,会得到这个错误。
发布于 2022-10-11 06:23:57
next()只能读取输入到空格。它不能读两个由空格隔开的单词。另外,next()在读取输入后将光标放在同一行中。
nextLine()读取输入,包括单词之间的空格(也就是说,它读取到行尾\n)。读取输入后,nextLine()将光标定位到下一行。
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
String b = scan.next();
boolean c = scan.nextBoolean();
System.out.println(a);
System.out.println(b);
System.out.println(c);
}发布于 2022-10-11 06:52:15
因此,如果确实需要使用nextLine(),基本上可以使用next()代替nextLine()或重新排序
b = scanner.nextLine();
a = scanner.nextInt();
c = scanner.nextBoolean();https://stackoverflow.com/questions/74023687
复制相似问题