我写了一个基本代码来读取不同的数据类型。但我无法输入字符串作为输入。我错过了什么?
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int integer = read.nextInt();
double Double = read.nextDouble();
String string = read.nextLine();
System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);
}
}
最佳答案
您必须“吃掉”双倍剩余的换行符。
Scanner read = new Scanner(System.in);
int integer = read.nextInt();
double Double = read.nextDouble();
read.nextLine();
String string = read.nextLine();
System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);
问题是在 nextDouble()
之后仍然有一个换行符,所以扫描器会读取下一行,但其中没有任何内容...
关于java - 与扫描器类混淆 -> nextLine(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31725979/