0

How to write a program using SWITCH that accepts input from the user and that input can be used to compute the users age?

This is my code: import java.util.Scanner; public class OctoberAge { public static void main(String[] args) { // Accept input from the user and that input can beused to compute the users age. // if the age is less than 10 months old, you're an infant. // 10 months - 2 years old = you're a baby // 3 - 15 years old = you're a kid // 16 - 18 years old = you're a teenager // 19 - 99 years old = you're an adult // 100 - 100+ years old = you're dead Scanner sc = new Scanner(System.in); int UserYear; int UserMonth; int a; System.out.println("Please input your year of birth: ") System.out.print("Year: ") UserYear = sc.nextInt(); a = (2018 - UserYear); System.out.println("Your age is" + a); switch(a) { case 1: System.out.println("you're a baby") break; case 2: System.out.println("you're a kid") break; case 3: System.out.println("you're a teenager") break; case 4: System.out.println("you're an adult") break; case 5: System.out.println("you're dead") break;

3rd Oct 2018, 1:03 PM
John Kevin Laurencio
John Kevin Laurencio - avatar
5 Respuestas
+ 2
if (age < 3) { //... } else if (age < 16) { //... } else if (...) { //... }
3rd Oct 2018, 8:12 PM
Anna
Anna - avatar
0
my code is not right but can someone help me with this? need some help for a fellow beginner programmer.
3rd Oct 2018, 1:04 PM
John Kevin Laurencio
John Kevin Laurencio - avatar
0
i guess i dont fit in programming :< Its so damn hard.
3rd Oct 2018, 1:05 PM
John Kevin Laurencio
John Kevin Laurencio - avatar
0
Make sure every statement ends with a semicolon. Other than that, I don't see any dramatic mistakes. It's just that you can't use a switch statement to check for a range of numbers. Right now, you're checking if a is 1 or 2 or 3 etc., but you want to know if it is less than 2 (infant), between 3 and 15 (kid) etc. I think the closest you can get using a switch statement would be something like switch (a) { case 0: case 1: case 2: // infant break; case 3: case 4: //... case 15: // kid break; } You would basically need to do that 100 times in a row to check all possible numbers. I think a nested if else works better in your case.
3rd Oct 2018, 1:34 PM
Anna
Anna - avatar
0
This is hard.
3rd Oct 2018, 7:50 PM
John Kevin Laurencio
John Kevin Laurencio - avatar