在Java计算器1.0的基础上进行了修改,从原有的变量固定值升级为键盘输入任意double类型的变量值,又新增了calculation方法,减少了main方法中的代码量。
package method;
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
System.out.println(calculation());
}
public static double add(double a, double b){
return a+b;
}
public static double reduce(double a,double b){
return a-b;
}
public static double ride(double a,double b){
return a*b;
}
public static double except(double a,double b){
if(b==0){
System.out.println("除数不能为0");
return 0;
}else{
return a/b;
}
}
public static double calculation(){
double sum=0;
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
System.out.println("请输入数字a");
double a=sc.nextDouble();
System.out.println("请输入运算符");
String f=sc1.next();
System.out.println("请输入数字b");
double b=sc2.nextDouble();
switch (f){//通过对f的判断选择计算方法
case "+":
sum=add(a,b);
break;
case "-":
sum=reduce(a,b);
break;
case "*":
sum=ride(a,b);
break;
case "/":
sum=except(a,b);
break;
default:
System.out.println("符号输入错误");
}
sc.close();
sc1.close();
sc2.close();
return sum;
}
}
|