接收2个浮点型数,返回相应操作结果:
//加法 public static double add(double num1,double num2){ return num1+num2; } //减法 public static double decrease(double num1,double num2){ return num1-num2; } //乘法 public static double multiplication(double num1,double num2){ return num1*num2; } //除法 public static double division(double num1,double num2){ return num1/num2; }
Scanner scanner = new Scanner(System.in); System.out.println("请输入第一个数字:"); double num1 = scanner.nextDouble(); System.out.println("请输入运算符:"); String operator = scanner.next(); System.out.println("请输入第二个数字:"); double num2 = scanner.nextDouble(); double result = 0; switch (operator){ case "+": result = add(num1,num2); break; case "-": result = decrease(num1,num2); break; case "*": result = multiplication(num1,num2); break; case "/": result = division(num1,num2); break; default: System.out.println("非法输入!"); } System.out.println(result); scanner.close();