In this program, I have to check the range of a given age and then print a message as per the age. I want to optimize the if else logic.
/* Sample code to read in test cases:*/
import java.io.*;
public class Main {
public static void main (String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
while ((line = buffer.readLine()) != null) {
line = line.trim();
// Process line of input Here
int age = Integer.parseInt(line);
if(age>=0 && age<=2){
System.out.println("Still in Mama's arms");
// break;
}else if(age>=3 && age<=4){
System.out.println("Preschool Maniac");
// break;
}else if(age>=5 && age<=11){
System.out.println("Elementary school");
// break;
}else if(age>=12 && age<=14){
System.out.println("Middle school");
// break;
}else if(age>=15 && age<=18){
System.out.println("High school");
// break;
}else if(age>=19 && age<=22){
System.out.println("College");
// break;
}else if(age>=23 && age<=65){
System.out.println("Working for the man");
// break;
}else if(age>=66 && age<=100){
System.out.println("The Golden Years");
//break;
}else{
System.out.println("This program is for humans");
}
}
}
}
Is there any other way to do this program? Using a switch, it becomes more complex to type with so many cases for the age.
(age >= ...
parts - they're covered by the previous checks already. \$\endgroup\$