atodeh
atodeh

Reputation: 45

Java: Trouble taking user input

and while trying to make this simple program, im having trouble getting user input in terms of the string. When entering the integer, im having no problems, but when my program asks the user to enter another a character, the cursur will blink waiting for me to type in something, but it wont let me. If i comment out all of the integer stuff, i am then allowed to enter a string. Is there a reason i cant input both? thank you

import java.util.Scanner;

public class math {
public static void main(String args[]){
    int int1,int2,int3;
    String operator;
    Scanner ahmad=new Scanner(System.in);
    System.out.print("Enter three integers: ");
    int1=ahmad.nextInt();
    int2=ahmad.nextInt();
    int3=ahmad.nextInt();
    System.out.print("Enter a (for average), s (for sum) or p (for product):");
    operator=ahmad.nextLine();
    System.out.println("Thank you");



}

}

Upvotes: 0

Views: 93

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

nextInt() only consumes the integer, it doesn't consume the whitespace characters (EOL in this case). Use two nextLine(), one to consume the EOL character, one to prompt you for input.

System.out.print("Enter a (for average), s (for sum) or p (for product):");
operator=ahmad.nextLine();
operator=ahmad.nextLine();

System.out.println("Thank you");

Upvotes: 3

Related Questions