/* switch statement. a multiway if/branch. Lots of syntax: 4 keywords (switch, case, break, default) switch (expression) { //Expr usually a variable or method call //that evaluates to an integer or char only. case constant: //case values must be constants, not variables. //integral (int and char only). Not double, not string. stmts //The first case value that matches the expr, //its stmts executed. break; // terminates the switch. //Else will fall thru to next case's stmts case constant: stmts break; case constant: case constant: // either of two values stmts break; // can have as many cases as needed default: // optional. Catch-all, will execute if none //of the cases matched stmts } //end of switch switch has limited use: selecting one of a few integral values. Any switch statement can be turned into cascaded else if structure (but not vice versa). */ //simple calculator example import java.awt.*; import javax.swing.*; public class SwitchTest extends JApplet { public static void main(String[] argv) { //public void init() { String input; input = JOptionPane.showInputDialog( null, "1. Addition\n"+ "2. Subtraction\n"+ "3. Multiplication\n"+ "4. Division\n"); int choice; choice = Integer.parseInt(input); input = JOptionPane.showInputDialog( null, "Enter first number"); int num1 = Integer.parseInt(input); input = JOptionPane.showInputDialog( null, "Enter second number"); int num2 = Integer.parseInt(input); int result; switch (choice) { case 1: result = num1 + num2; break; case 2: result = num1 - num2; break; case 3: result = num1 * num2; break; case 4: result = num1 / num2; break; default: result = 0; } JOptionPane.showMessageDialog(null, "Result = "+result); } }