chandler11able
chandler11able

Reputation: 123

Why Wont My Java Scanner Take In input?

package Lessons;

import java.util.Scanner;

public class Math {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("please enter the first number of your question! ");
        int a1 = s.nextInt();
        System.out.print("So you chose " + a1);
        System.out.println(" Choose ur second number");
        int a2 = s.nextInt();
        System.out.print("You chose " + a2 + " for your second number");
        System.out.print(" Now enter ur operator ");
        String b1 = s.nextLine();
        if (b1.equalsIgnoreCase("-")) {
            System.out.println("You chose " + b1 + "as ur operator");
        }
    }

}

I do not understand why line 15 does not take any input, any help would be appreciated:3

Output

please enter the first number of your question! 2552 So you chose 2552 Choose ur second number 41 You chose 41 for your second number Now enter ur operator

Output ends and stops at the last line for some reason and does not take any information!

Upvotes: 2

Views: 91

Answers (3)

SamTebbs33
SamTebbs33

Reputation: 5657

You need to call in.nextLine() right after the line where you call in.nextInt() The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine().

int a2 = s.nextInt();
s.nextLine();

This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line, such as when you call nextBoolean() etc.

Upvotes: 3

danleyb2
danleyb2

Reputation: 1068

Try this for the section of taking a String input.

`System.out.print(" Now enter ur operator ");
    String b1 =s.next();
    if (b1.equalsIgnoreCase("-")) {
        System.out.println("You chose " + b1 + "as ur operator");
}`

Upvotes: 0

emjay
emjay

Reputation: 440

Calling s.nextInt() reads the next int, but does not read the new line character after that. So the new line would be read on line 15. If you are sure that every input will be put in a separate line, then you can resolve this problem by putting an extra s.nextLine() before line 15:

...
System.out.print(" Now enter ur operator ");
s.nextLine();
String b1 = s.nextLine();
...

Upvotes: 1

Related Questions