Java 计算器
要求:实现加减乘除操作,并且能够循环计算数据,通过与用户交互实现。
package com.wzt.method;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("请输入第一个数字:");
double first = scanner.nextDouble();
System.out.println("请输入第二个数字:");
double second = scanner.nextDouble();
System.out.println("请输入运算符:");
String operator = scanner.next();
if (operator.equals("quit")){
System.out.println("退出计算器");
break;
}
switch (operator){
case "+" :
System.out.println("计算结果是:" + add(first,second));
break;
case "-" : System.out.println("计算结果是:" + sub(first,second));
break;
case "*" : System.out.println("计算结果是:" + mul(first,second));
break;
case "/" : System.out.println("计算结果是:" + div(first,second));
break;
}
}
scanner.close();
}
//加法
public static double add(double a, double b){
return a+b;
}
//减法
public static double sub(double a, double b){
return a-b;
}
//乘法
public static double mul(double a, double b){
return a*b;
}
//除法
public static double div(double a, double b){
return a/b;
}
}