Scratch Fever
Scratch Fever

Reputation: 35

Scanner input skipping next input

I am now having a difficult time fixing this problem. So, I have this code snippet here which asks 3 input from the user.

 case 0:
      String accnum,pin,name;
      System.out.print("Enter account name: ");
      name = input.nextLine();
      System.out.print("Enter account number: ");
      accnum = input.next();
      System.out.print("Enter account PIN: ");
      pin = input.next();
      atm.set_accinfos(name,accnum,pin);
      //System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
    break;

But everytime I run it, it always skips the input for the String "name", I tried using input.next(); on it and it works but then it will now skip the input for String "accnum".

EDIT: It also just happens if the input from "name" has a space on it, for example : John Doe.

Am I missing something here?

Upvotes: 2

Views: 2083

Answers (4)

Scratch Fever
Scratch Fever

Reputation: 35

Okay, thats for the help everyone, I managed to fix it by adding "input.nextLine();" before "name = input.nextLine();"

Upvotes: 0

Luke Willis
Luke Willis

Reputation: 8580

If you're using input anywhere before this block of code, then you need to be sure to call nextLine earlier on.

If you use next instead, then your input stream will still contain a new line character (\n). Thus, when you start this block of code with nextLine, that call will take the previous \n and not the name which was just entered.

In general, if your Scanner is reading System.in, then you should use nextLine everywhere. next, nextInt, and the other next methods are meant for more predictable data.

Upvotes: 0

Karunakar
Karunakar

Reputation: 2349

Try This. i think problem with next(). since next reads input as tokens with default delimiter(i think space is the default delimiter).:

case 0:
String accnum,pin,name;

System.out.print("Enter account name: ");
name = input.nextLine();

System.out.print("Enter account number: ");
accnum = input.nextLine();

System.out.print("Enter account PIN: ");
pin = input.nextLine();

atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

The nextLine() gobbles the newline character produced by the next() of account pin (when you hit enter). So, it won't ask for name. Add input.nextLine() after pin = input.next(); and try

Upvotes: 1

Related Questions