下面是题目与思路让大家写一个计算器
下方是提供参考的代码
import java.util.Scanner;
public class Counter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入a的值:");
double a = scanner.nextDouble();
System.out.println("输入运算符:");
String str = scanner.next(); //注意要使用next(),不能用nextLine()
System.out.println("输入b的值:");
double b = scanner.nextDouble();
switch (str){
case "+":
System.out.println(add(a,b));
break;
case "-":
System.out.println(reduce(a,b));
break;
case "*":
System.out.println(mutiply(a,b));
break;
case "/":
System.out.println(divides(a,b));
break;
default:
System.out.println("运算符输入错误!");
break;
}
scanner.close(); //每次使用完scanner记得关闭
}
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 mutiply(double a, double b){
return a * b;
}
public static double divides(double a, double b){
return a / b;
}
}
运行后: