1

I need to take two strings as input from user. I'm using Scanner.nextLine()

try {
    firstChoice = in.nextInt();
} catch(Exception e) {
    System.out.println("Invalid option");
}

if(firstChoice == 1) {
    if(accNumber < numOfAccounts)
    {
        System.out.print("Account Title: ");
        String t = in.nextLine();
        System.out.print("Account Holder's name: ");
        String name = in.nextLine();
        .....

But on the output window, it shows:

Account Title: Account Holder's name:

It's not waiting for the first input. Why's that? It works correctly with Scanner.next() but I want to read the complete lines as the name can consist of more than one part.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Abdul Jabbar
  • 2,573
  • 5
  • 23
  • 43

1 Answers1

1

nextInt reads only the int value and skips the \n (when you press enter key right after). You should add another nextLine right after the nextInt to consume the \n.

Update your code to:

try {
   firstChoice = in.nextInt();
   nextLine();
}

And you'll be fine.

Maroun
  • 94,125
  • 30
  • 188
  • 241