gpt4 book ai didi

java - Scanner.nextLine 输入跳过

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:15 24 4
gpt4 key购买 nike

我需要将两个字符串作为用户的输入。我正在使用Scanner.nextLine()

try {
firstChoice = in.nextInt();
} catch(Exception e) {
System.out.println("Invalid option");
}

if(firstChoice == 1) {
if(accNumber < numOfAccounts)
{
System.out.print("Account Title: ");
String t = in.nextLine();
System.out.print("Account Holder's name: ");
String name = in.nextLine();
.....

但是在输出窗口上,它显示:

Account Title: Account Holder's name:

它不等待第一个输入。为什么?它与 Scanner.next() 一起正常工作但我想阅读完整的行,因为名称可以由多个部分组成。

最佳答案

nextInt 读取int值并跳过\n(当您紧接着按enter键时)。您应该添加另一个 nextLine紧接在 nextInt 之后使用 \n

将您的代码更新为:

try {
firstChoice = in.nextInt();
nextLine();
}

你会没事的。

关于java - Scanner.nextLine 输入跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795970/

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