IMustBeSomeone IMustBeSomeone - 5 months ago 11
Java Question

Why is using Scanner's nextFoo() in an if statement alone slower than using it with a variable?

Question

Today, I was messing around with if statement's to test my program. When it came to testing some functions, I used Scanner to test multiple functions in one test run.

Here is how I wrote it first:

Spaceship spaceship = new Spaceship("Spaceship");
Scanner in = new Scanner(System.in);
spaceship.activate();
while(true) {

if (in.nextInt() == 1) {
spaceship.activateShields();
} else if (in.nextInt() == 2) {
spaceship.deactivateShields();
}
else if(in.nextInt() == 3) {
spaceship.deactivate();
}
}

}


On running, it worked fine, but it took longer for a response time and sometimes I'd have to write it twice. I wondered if it was an IDE problem. I went ahead, exported it and ran it in the Windows Command Processor. No difference. First, I thought it was something with my 'updateThread' in my Spaceship class. It didn't seem it was though, see below.

Here is how I wrote it the next time.

Spaceship spaceship = new Spaceship("Spaceship");
Scanner in = new Scanner(System.in);
spaceship.activate();
while(true) {
int choice = in.nextInt();
if (choice == 1) {
spaceship.activateShields();
} else if (choice == 2) {
spaceship.deactivateShields();
}
else if(choice == 3) {
spaceship.deactivate();
}
}

}


This time it worked perfect! There was absolutely no delay. Does anyone know why this is happening?

Answer

In the second example, you read one int value from the scanner. The first one contains three such nextInt() calls. The scanner is waiting for your input every time when it sees nextInt().

I will try to explain it more detailed.

if (in.nextInt() == 1) { // you typed `2` -> `false`
    spaceship.activateShields();
} else if (in.nextInt() == 2) { // we went here and the scanner is waiting for the input
    // you typed `2` -> true -> execute the block
    spaceship.deactivateShields();
} else if(in.nextInt() == 3) { // on this iteration we won't come here
    spaceship.deactivate();
}

int choice = in.nextInt(); // you typed `2`
// we are looking for a proper way
if (choice == 1) { // `false`
    spaceship.activateShields();
} else if (choice == 2) { // `true` -> execute and go to check the `while` condition
    spaceship.deactivateShields();
} else if(choice == 3) {
    spaceship.deactivate();
}
Comments