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

Show parent comments

2

u/Kittensandpuppies14 Feb 25 '24

And tell us what the actual error message is

1

u/Super_Good9981 Feb 25 '24

public class LifeStageIdentifier {

public static void main(String[] args) {

// Create a Scanner object to read input from the keyboard

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the person's age

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

// Read the input as an integer

int age = scanner.nextInt();

// Determine the person's stage of life based on age

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");

}

// Close the Scanner object

scanner.close();

}

}

1

u/Super_Good9981 Feb 25 '24

I wanted to print terms like Adult when i entered 21 and it just printed 21

-1

u/Kittensandpuppies14 Feb 25 '24

Go through it line by line or with a debugger. It’s literally printing 21 before it does anything else and doesn’t prompt the user for anything. Pro tip: try harder next time