r/learnjava • • Feb 25 '24

Java if else statement

System.out.print("40: ");

int age = scanner.nextInt();

if (age < 0 || age > 120) {

System.out.println("Invalid age");

} else if (age <= 12) {

System.out.println("Child");

} else if (age <= 19) {

System.out.println("Teenager");

} else if (age <= 64) {

System.out.println("Adult");

} else {

System.out.println("Senior Citizen");

}

I wanted to print a specific result but it wasn't coming up, what errors am i making

0 Upvotes

25 comments sorted by

View all comments

0

u/[deleted] Feb 25 '24

[deleted]

0

u/nekokattt Feb 25 '24 edited Feb 25 '24

how can an age be both less than zero and greater than 120 at the same time?

This is not their issue at all and the OR is perfectly valid there. Their code will be outputting something (even if it is totally wrong) if they run it. If they are getting zero output at all then it is a totally different issue and they have omitted some code if this thing actually compiles.

Please don't give confusing advice... and thanks for the downvote.

2

u/Super_Good9981 Feb 25 '24

If the age is less than 0 or greater than 120, print "Invalid age".

This is what i was trying to solve using if else statement

3

u/nekokattt Feb 25 '24

yes, and that is totally fine. The deleted comment was saying your logic is wrong but that is false. You did it correctly.

The comment was

bruh your logic is wrong your first if needs an AND rather than an OR to execute

which was nonsense.

The issue is you have a lot of missing code in your example. You have no main class, no main method, no import for the scanner class and you do not define the scanner object, so we can't help further.