Java扫描器跳过行

huangapple go评论82阅读模式
英文:

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&#39;m having some issues with Javas scanner, what I&#39;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(&quot;Please enter the name of person: &quot;);
                Client.SetName(kb.nextLine());
                System.out.println(&quot;Please enter the coin value for person: &quot;);
                Client.SetCoins(kb.nextInt());
                System.out.println(Client.GetName() + &quot; &quot; + Client.GetCoins());
                
                
                //Clients.add(Client);
              
                
                //Checks if user wants to loop
                System.out.print(&quot;Do you have another client to person (y/n)&quot;);
                bool = kb.next().trim().toLowerCase().charAt(0);
             }while(bool != &#39;n&#39;);

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

&gt; Exception in thread &quot;main&quot; java.util.InputMismatchException



</details>


# 答案1
**得分**: 1

尝试将"nextLine"更改为"next",在获取输入时获取名称。

<details>
<summary>英文:</summary>

Try changing nextLine to next while getting name as input

</details>



huangapple
  • 本文由 发表于 2020年9月11日 16:18:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63843334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定