简易计算器
要求:
- 写四个方法:加、减、乘、除
- 利用switch语句
- 传递需要操作的两个数
- 输出结果
代码:
package com.dou.method;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
// 简易计算器
Scanner scanner = new Scanner(System.in);
double result = 0;
System.out.println("请输入计算式!");
int a = scanner.nextInt();
String f = scanner.next();
int b = scanner.nextInt();
switch (f){
case "+":
result = add(a,b);
break;
case "-":
result = sub(a,b);
break;
case "*":
result = mul(a,b);
break;
case "/":
result = div(a,b);
break;
}
System.out.println("计算结果为: "+ a + f + b + "= " + result);
}
public static double add(int x1, int x2){
return x1+x2;
}
public static double sub(int x1, int x2){
return x1-x2;
}
public static double mul(int x1, int x2){
return x1*x2;
}
public static double div(int x1, int x2){
return x1/x2;
}
}
结果