簡體   English   中英

為什么有時會跳過input.next()?

[英]Why is input.next() sometimes being skipped?

在我的代碼(如下)中, input.next(); 只是被跳過了。 有人可以指出原因嗎?

for (int i=0; i<empNum; i++)//for each employee they want to work with
    {
        System.out.print("\r\n\r\nPROFILE FOR EMPLOYEE #" + (i+1) + ":\r\n"
                        +"type Hourly(1), Salaried(2), Salaried plus Commission(3)\r\n"
                        +"Enter 1, 2, or 3 ==> ");//display type gathering
        int typeChooser = input.nextInt();//gather type

        System.out.print("Name ==> ");//ask for name
        String name = input.next();//get name

        System.out.print("Social Security Number ==> ");//ask for ssn
        String ssn = input.next();//THIS PART IS SKIPPED

        System.out.print("Birthday Month (1-12) ==> ");//ask for bdayMonth
        int bdayMonth = input.nextInt();//get bdayMonth

        System.out.print("Birthday bonus week (1-4) ==> ");//ask for bdayWeek
        int bdayWeek = input.nextInt();//get bdayWeek            
}

編輯:我只是注意到,唯一一次被跳過的是名稱中有空格的情況(即鮑勃·史密斯而不是鮑勃)

社會安全號碼是否包含空格? 如果是這樣,您可以嘗試nextLine();。 方法。 此方法返回當前行的其余部分,但不包括最后的任何行分隔符。

System.out.print("Social Security Number ==> ");//ask for ssn
String ssn = input.nextLine();

我假設您為此使用Scanner 掃描程序默認情況下使用空格作為定界符,因此next()方法將只讀取直到下一個空格,而不是末尾字符。 因此,如果輸入中有空格,則應改用nextLine()方法。

從Umut的答案中,您的代碼看起來像

 input.nextLine();
 System.out.print("Social Security Number ==> ");//ask for ssn
 String ssn = input.nextLine();

您需要首次調用nextLine()因為input.next()不會前進到換行符之前

由於在文檔中闡明這里

公共字符串next()

查找並返回此掃描儀的下一個完整令牌。 完整的標記在其前面,然后是與定界符模式匹配的輸入。 即使先前調用hasNext()返回true,此方法也可能在等待輸入掃描時阻塞。

因此,當名稱輸入中有空格時,next()僅返回第一個標記,因為其默認定界符為空格字符,因此其余標記仍在緩沖區中,然后在緩沖區中首先讀取在調用next()之后。 在這里使用nextLine()占用整行(默認分隔符為'\\ n'),或者您可以更喜歡使用BufferedReader。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM