Possible Duplicate:
If/Else vs. Switch
I have two codes here, i just wanted to ask which of the two is better in terms of writability(ease of writing the codes) and in terms of readability (ease of understanding the codes).
switch-case:
import java.io.*;
public class Quarter{
public static void main(String[] args){
int day;
String input="";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Input a number from 1 to 3: ");
try{
input=in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
day=Integer.parseInt(input);
switch(day){
case 1:
case 2:
case 3:
System.out.println("1st Quarter");
break;
case 4:
case 5:
case 6:
System.out.println("2nd Quarter");
break;
case 7:
case 8:
case 9:
System.out.println("3rd Quarter");
break;
case 10:
case 11:
case 12:
System.out.println("4th Quarter");
break;
default: System.out.println("Error!");
}
}
}
if-else:
import java.io.*;
public class Days{
public static void main(String[] args){
int day;
String input="";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Input a number from 1 to 12: ");
try{
input=in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
day=Integer.parseInt(input);
if(day>=1 && day<=3){
System.out.println("1st Quarter");
}else
if(day>=4 && day<=6){
System.out.println("2nd Quarter");
}else
if(day>=7 && day<=9){
System.out.println("3rd Quarter");
}else
if(day>=10 && day<=12){
System.out.println("4th Quarter");
}else
System.out.println("Error!");
}
}
Neither, I'd do this one:
String[] out = {
"1st Quarter",
"2nd Quarter",
"3rd Quarter",
"4th Quarter"
};
if (1 <= day && day <= 12) {
System.out.println(out[(day - 1) / 3]);
} else {
System.out.println("Error!");
}
Avoid the need for the logic to branch in the first place. Table lookup is often a useful technique. Arithmetic manipulation is also important - look for a pattern in the values you care about, and a function that transforms them into something simpler. Also consider polymorphism in more complex cases.
If you are handling all the exceptions the same way, then do it in the same place.
Scope variables tightly where possible.
Prompt for the input you actually want, FFS. :)
import java.io.*;
public class Quarter {
public static void main(String[] args) {
try {
System.out.print("Input the month number (1 = January, 2 = February ... 12 = December): ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int month = Integer.parseInt(in.readLine());
int quarter = (month - 1) / 3;
String[] quarters = new String[]{ "1st", "2nd", "3rd", "4th" };
System.out.println(quarters[quarter] + " Quarter");
} catch (Exception e) { // IOException for non-numeric, or AIOOBE for out of range
System.out.println("Error!");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With