gpt4 book ai didi

Java scan.nextLine() 只等待int用户输入的用户输入;不等待字符串用户输入

转载 作者:行者123 更新时间:2023-12-01 15:17:25 24 4
gpt4 key购买 nike

Possible Duplicate:
java, programm not stopping for scan.nextLine()

    System.out.println("Welcome to the Tuition Calculator Program.");
System.out.println("How many total credits are you taking?");
credits = scan.nextInt();

System.out.println("Are you a Washington resident? y/n");
resident = scan.nextLine();

System.out.println("Are you a graduate student? y/n");
grad = scan.nextLine();

我是 Java 新手,对于编程也比较陌生。在运行 jGRASP 的 PC 上。在上面的代码中,我只需要用户输入学分(int 响应)、居住地(字符串)和毕业生身份(字符串)。

它允许用户输入学分,然后将居民问题和毕业生问题一起打印。它不会停止并允许用户输入居住问题的答案。 (它确实允许我输入对毕业生问题的回答。)

论坛上的其他相关问题没有帮助;我尝试添加一条额外的行来吞掉任何额外的换行符,但这并没有成功。也许我添加了错误的线路类型。 This thread很有帮助,但没有提供有效的解决方案。

最佳答案

为什么会发生这种情况?
如果您尝试打印resident,您会发现它打印newline字符。实际上这里发生的事情是这样的。输入credits后按下的回车键将被作为字符串ans复制到resident变量中。所以你需要的是避免换行符。
解决方案
使用 nextLine() 读取 credits 并使用 Integer.parseInt() 将其解析为整数。

 System.out.println("Welcome to the Tuition Calculator Program.");  
System.out.println("How many total credits are you taking?");
credits = Integer.parseInt(scan.nextLine());
System.out.println("Are you a Washington resident? y/n");
resident = scan.nextLine();
System.out.println("Are you a graduate student? y/n");
grad = scan.nextLine();

关于Java scan.nextLine() 只等待int用户输入的用户输入;不等待字符串用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11444473/

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