How to write a program using switch and if else statement that accepts input from the user and used to compute the users age? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to write a program using switch and if else statement that accepts input from the user and 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, 7:43 PM
John Kevin Laurencio
John Kevin Laurencio - avatar
1 Answer
0
If you are trying to find a range then you can't use a switch so I would just use if and else if statements. Here is some example code: System.out.println("How old are you?"); Scanner sc = new Scanner(System.in); double userAge = sc.nextDouble(); if ((userAge*12) < 10) { //finds months and if age is less than 10 months, print infant System.out.println("You're an infant!"); } else if (((userAge*12) >= 10) && (userAge <= 2)) { //if in range of 10 months and 2 years System.out.println("You're a baby!"); } else if ((3 <= userAge) && (15 >= userAge)) { System.out.println("You're a kid!"); } else if ((16 <= userAge) && (18 >= userAge)) { System.out.println("You're a teenager!"); } else if ((19 <= userAge) && (99 >= userAge)) { System.out.println("You're an adult!"); } else if (userAge >= 100) { System.out.println("You're dead!"); }
3rd Oct 2018, 8:44 PM
Jerid Derply
Jerid Derply - avatar