方法一:
package com.liaojianya.chapter1; import java.util.Scanner; public class SwitchDemo1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter number a : "); double a = input.nextDouble(); System.out.println("Enter number b : "); double b = input.nextDouble(); Action ac = new Action(a, b); ac.command(Action.ADD); ac.command(Action.SUBTRACT); ac.command(Action.MULTIPLY); ac.command(Action.DIVIDE); ac.command(Action.MOD); input.close(); } } class Action { double a; double b; public Action(double a, double b) { this.a = a; this.b = b; } public static final int ADD = 1; public static final int SUBTRACT = 2; public static final int MULTIPLY = 3; public static final int DIVIDE = 4; public static final int MOD = 5; public void command(int c) { switch (c) { case 1: System.out.println(a + " + " + b + " = " + (a + b)); break; case 2: System.out.println(a + " - " + b + " = " + (a - b)); break; case 3: System.out.println(a + " * " + b + " = " + (a * b)); break; case 4: System.out.println(a + " / " + b + " = " + (a / b)); break; case 5: System.out.println(a + " % " + b + " = " + (a % b)); break; default: System.out.println("unknown operation!"); break; } } }
方法二:
package com.liaojianya.chapter1; import java.util.Scanner; /** * This program demonstrates the use of switch. * @author LIAO JIANYA * */ public class SwitchDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter number a : "); double a = input.nextDouble(); System.out.println("Enter number b : "); double b = input.nextDouble(); System.out.println("Enter operater :1代表+,2代表-,3代表*,4代表/,5代表% "); int c = input.nextInt(); switch(c) { case 1: System.out.println(a + " + " + b + " = " + (a + b)); break; case 2: System.out.println(a + " - " + b + " = " + (a - b)); break; case 3: System.out.println(a + " * " + b + " = " + (a * b)); break; case 4: System.out.println(a + " / " + b + " = " + (a / b)); break; case 5: System.out.println(a + " % " + b + " = " + (a % b)); break; default: System.out.println("unknown operation!"); break; } } }
运行结果:
Enter number a : 12.3 Enter number b : 32.1 12.3 + 32.1 = 44.400000000000006 12.3 - 32.1 = -19.8 12.3 * 32.1 = 394.83000000000004 12.3 / 32.1 = 0.38317757009345793 12.3 % 32.1 = 12.3