gpt4 book ai didi

java - 与扫描器类混淆 -> nextLine()

转载 作者:行者123 更新时间:2023-11-29 03:06:55 27 4
gpt4 key购买 nike

我写了一个基本代码来读取不同的数据类型。但我无法输入字符串作为输入。我错过了什么?

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com