Zack Guetta Zack Guetta - 1 year ago 76
Java Question

Scanner input reading multiple lines of code at once, throws IntputMismatchException

Okay so, I have this piece of code:

if (type == 1){
System.out.println("Agency name: ");
agencyName = in.nextLine();

System.out.println("No. of days: ");
days = in.nextInt();

Patuvanje p = new PraznicnoPatuvanje (agencyName, 20, days);
nizaPatuvanje[i] = p;

The scanner is reading 'agencyName' and 'days' without me trying to input the agencyName at first. What code should I add so that the compiler would wait until I initialize the agencyName variable, and then let me assign the 'days' variable.

This is how it looks like in the Console:

enter image description here

Answer Source

In the code preceding this, you are reading the number of vacations

After doing this you are pressing Enter This needs to be consumed too.

Change your code to

in.nextLine (); // comse previouslt entered `Enter`
System.out.println("Agency name: ");
agencyName = in.nextLine();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download