Kulahan
Kulahan

Reputation: 522

Why is input.next() sometimes being skipped?

In my code (below), the input.next(); is just skipped. Can someone please point out why?

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            
}

EDIT: I just noticed that the only time it's skipped is when the name has a space in it (i.e. Bob Smith instead of just Bob)

Upvotes: 0

Views: 87

Answers (4)

devautor
devautor

Reputation: 2586

As stated in the docs here

public String next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

So, when you have a space in your name input, next() returns only the first token, since its default delimiter is a space character and so remaining token(s) is/are still in the buffer which are then read first on the following call to next(). Use nextLine() here to eat up the whole line (default delimiter is '\n' for it), or you can prefer using BufferedReader instead.

Upvotes: 0

Umut D.
Umut D.

Reputation: 1846

Does Social Security Number contains whitespace? If it does, You can try nextLine(); method. This method returns the rest of the current line, excluding any line separator at the end.

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

Upvotes: 1

Michael
Michael

Reputation: 2773

Taking from Umut's answer, your code would look something like

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

You need that first call to nextLine() because input.next() will not advance past the newline token

Upvotes: 1

Rothens
Rothens

Reputation: 815

I assume you use a Scanner for this. Scanner by default uses whitespaces as a delimiter, so the next() method will only read until the next space, not the endline character. So if there are spaces in the input, you should use nextLine() method instead.

Upvotes: 1

Related Questions