0

User Input with "If" and "else".

I was testing out if I can use the "if" and "else " operators, this is what I wanted to do. I want to get the user input and verify the user's age with the "if" and "else", for example, if the user put's a number like 20 It will displays a message that says "You are an older person with an age of <User Input>", and if the person put's something else that's under the number of 18 it will display a message that says "You are too young". I try to recreate that with this code: Scanner age = new Scanner(System.in); if (age >= 18){ System.out.println ("You are an older person with an age of " + age.nextInt()); } else { System.out.println ("You are too young"); } But when I put the age, it says that Scanner it's not an 'int'. How can I make those things possible?

4th Aug 2018, 8:19 PM
José Ortega
José Ortega - avatar
2 Antworten
+ 4
That happens because you are using the Scanner badly. First you need to create the Scanner, and later you use it to get what you want. Your code should look like this: import java.util.Scanner; public class Program { public static void main(String[] args) { int age; Scanner sc = new Scanner(System.in); age = sc.nextInt(); if (age >= 18){ System.out.println ("You are an older person with an age of " + age); } else { System.out.println ("You are too young"); } } }
4th Aug 2018, 8:31 PM
Mickel
Mickel - avatar
+ 1
Thank you my dude
4th Aug 2018, 9:49 PM
José Ortega
José Ortega - avatar