Switch Case dalam Java
- ..
Penyeleksian switch digunakan untuk memeriksa nilai-nilai yang mungkin dari sebuah ekspresi. Ekspresi yang diperiksa harus bertipe int, short, char atau byte.
package switchcase; import java.io.BufferedReader; import java.io.InputStreamReader; /** * * @author fian */ public class SwitchCase { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { int x, y; //untuk menangkap inputan dari keyboard BufferedReader object = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter two numbers for operation:"); try { x = Integer.parseInt(object.readLine()); //membaca inputan dari keyboard y = Integer.parseInt(object.readLine()); System.out.println("1. Add"); System.out.println("2. Subtract"); System.out.println("3. Multiply"); System.out.println("4. Divide"); System.out.println("enter your choice:"); int a = Integer.parseInt(object.readLine()); //parsing inputan ke type integer switch (a) { case 1: //jika pilahan 1 System.out.println("Enter the number one=" + (x + y)); break; case 2: //jika pilihan 2 System.out.println("Enter the number two=" + (x - y)); break; case 3: //jika pilihan 3 System.out.println("Enetr the number three=" + (x * y)); break; case 4: //jika pilihan 4 System.out.println("Enter the number four=" + (x / y)); break; default: //selain di atas System.out.println("Invalid Entry!"); } } //penanganan jika ada kesalahan pada execution di atas catch (NumberFormatException ne) { //menampilkan pesan kesalahan System.out.println(ne.getMessage() + " is not a numeric value."); System.exit(0); //keluar } } }