英文:
Java Scanner Skipping Line
问题
以下是翻译好的部分:
我遇到了一些关于Java扫描器的问题,我想要做的是获取输入并将其放入对象中并循环,直到用户不想继续为止,第一次循环中一切正常,但在第二次循环中,扫描器跳过了输入姓名的步骤。
我的代码:
do
{
//提示用户输入对象变量
System.out.println("请输入人的姓名:");
Client.SetName(kb.nextLine());
System.out.println("请输入人的硬币价值:");
Client.SetCoins(kb.nextInt());
System.out.println(Client.GetName() + " " + Client.GetCoins());
//检查用户是否想要循环
System.out.print("是否有另一个客户要输入(y/n)");
bool = kb.next().trim().toLowerCase().charAt(0);
}while(bool != 'n');
控制台输出:
请输入人的姓名:
test
请输入人的硬币价值:
5
test 5
是否有另一个客户要输入(y/n)y
请输入人的姓名:
请输入人的硬币价值:
10
10
是否有另一个客户要输入(y/n)y
请输入人的姓名:
请输入人的硬币价值:
test
在线程“main”中出现异常java.util.InputMismatchException
<details>
<summary>英文:</summary>
I'm having some issues with Javas scanner, what I'm trying to do is get inputs and put them into objects and loop that until the user says so, everything works fine on the first loop but on the second loop the scanner skips inputting the name.
My code:
do
{
//Prompts user for object variables
System.out.println("Please enter the name of person: ");
Client.SetName(kb.nextLine());
System.out.println("Please enter the coin value for person: ");
Client.SetCoins(kb.nextInt());
System.out.println(Client.GetName() + " " + Client.GetCoins());
//Clients.add(Client);
//Checks if user wants to loop
System.out.print("Do you have another client to person (y/n)");
bool = kb.next().trim().toLowerCase().charAt(0);
}while(bool != 'n');
Console Log:
Please enter the name of person:
test
Please enter the coin value for person:
5
test 5
Do you have another client to person (y/n)y
Please enter the name of person:
Please enter the coin value for person:
10
10
Do you have another client to person (y/n)y
Please enter the name of person:
Please enter the coin value for person:
test
> Exception in thread "main" java.util.InputMismatchException
</details>
# 答案1
**得分**: 1
尝试将"nextLine"更改为"next",在获取输入时获取名称。
<details>
<summary>英文:</summary>
Try changing nextLine to next while getting name as input
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论