I'm trying to create a program that guesses the user's age and I'm having some trouble. Here is my code:
System.out.println("Let me guess your age.");
System.out.println("Enter remainders of dividing your age by 3, 5 and 7.");
// reading all remainders
Scanner remainder3 = new Scanner(System.in);
Scanner remainder5 = new Scanner(System.in);
Scanner remainder7 = new Scanner(System.in);
int age = ((remainder3 * 70 (remainder5 * 21) (remainder7 * 15)) % 105);
System.out.println("Your age is " age " that's a good time to start programming!");
When I run the program I get this error:
java: bad operand types for binary operator '*'
first type: java.util.Scanner
second type: int
What can I do to debug this program?
I think it's an issue of the age variable not recognizing the variable type "int," so I tried changing that. I also tried adding parentheses but that did not work either.
CodePudding user response:
public static void main(String[] args) {
Scanner keypressReader = new Scanner(System.in);
System.out.println("Let me guess your age.");
System.out.println("What is the remainder of dividing your age by 3?");
int re3 = keypressReader.nextInt();
System.out.println("What is the remainder of dividing your age by 5?");
int re5 = keypressReader.nextInt();
System.out.println("What is the remainder of dividing your age by 7?");
int re7 = keypressReader.nextInt();
int age = ((re3 * 70 (re5 * 21) (re7 * 15)) % 105);
System.out.println("Your age is " age " that's a good time to start programming!");
}
Based on what's stated by commenters. this is the basic of how to use Scanner to read integer inputs.
- Start off by creating a Scanner object.
- Use System.out.println to have your program interact with the user with a question or a call to action.
- Use Scanner functions like nextLine, nextDouble, nextInt, etc to get the values from user inputs.
- Conduct your processing of the inputs by the user.
To get a better grade and impress your teacher, you should look into how to cater for error inputs. e.g. what if the user enter alphabets instead of a numerical value?
CodePudding user response:
You have to use scanner.nextLine()
to read input. Currently, you are trying to multiply the Scanner itself with a number, which throws an error.
You can declare one Scanner with new Scanner(System.in)
and then read the lines as follows:
int remainder3 = Integer.valueOf(scanner.nextLine());
int remainder5 = Integer.valueOf(scanner.nextLine());
int remainder7 = Integer.valueOf(scanner.nextLine());