Ask coding questions

← Back to all posts
1
Java question
AlieksieiBiespa (0)

Why it works
float x, y;
Scanner input = new Scanner(System.in);
System.out.print("Math operation:");
String mat_op = input.nextLine();
System.out.print("Input num1:");
x = input.nextFloat();
System.out.print("Input num2");
y = input.nextFloat();

    switch (mat_op) {
        case "+": System.out.println("Result = "+(x+y));
        break;
        case "-": System.out.println("Result = "+(x-y));
            break;
        default: System.out.println("Wrong op");
    }

but this not works
float x, y;
Scanner input = new Scanner(System.in);
System.out.print("Input num1:");
x = input.nextFloat();
System.out.print("Input num2");
y = input.nextFloat();
System.out.print("Math operation:");
String mat_op = input.nextLine();

    switch (mat_op) {
        case "+": System.out.println("Result = "+(x+y));
        break;
        case "-": System.out.println("Result = "+(x-y));
            break;
        default: System.out.println("Wrong op");
    }
Answered by mwilki7 (117) [earned 5 cycles]
View Answer
Commentshotnewtop
1
mwilki7 (117)

I ran your code on an online java compiler and saw the problem you were experiencing. If you'd like a clearer explanation try: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo

Why the second one doesn't work:

When you read an integer before a string like:

int number = input.nextInt();
String word = input.nextLine();

Say your input sequence looks like this:

int number = 1234 [enter key];
String word = "hello";

[enter key] turns into a new line character -> "\n" meaning you are ready to send your input
Numbers don't keep newline characters so it's not taken from your input.

int number = 1234 [enter key];
String word = "hello";

Turns into:

int number = 1234;
String word = [enter key] "hello"

Scanner reads [enter key] immediately and doesn't even proceed to get "hello" from input.

You can get rid of this saved "enter key/newline character" by calling input.nextLine() again like this:

int number = input.nextInt();
input.nextLine(); // read the newline character here
String word = input.nextLine(); // now i get "hello"

Why the first one works:

nextLine() will keep the [enter key] character so the next time scanner takes input again it will be valid input like you would expect

1
AlieksieiBiespa (0)

swapped
System.out.print("Math operation:");
String mat_op = input.nextLine();