calculator
package com.wang.method;
import java.util.Scanner;
public class HomeWork03 {
public static void main(String[] args) {
cal();
while (true){
System.out.println("是否继续使用独家专用计算器?如果是请输入“start”,否则输入其他任意按键退出当前程序!");
Scanner scanner = new Scanner(System.in);
String trigger = scanner.next();
if (trigger.equals("start")){
cal();
}else{
System.out.println("感谢您的使用!");
System.exit(0);
scanner.close();
}
}
}
//循环使用计算器
public static void cal() {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎使用独家专用计算器!");
System.out.println("请输入第一个需要计算的值:");
Scanner scanner1 = new Scanner(System.in);
double num1 = scanner1.nextDouble();
System.out.println("请输入“+”或“-”或“*”或“/”进行运算:");
Scanner scanner3 = new Scanner(System.in);
String operator = scanner3.next();
System.out.println("请输入第二个需要计算的值:");
Scanner scanner2 = new Scanner(System.in);
double num2 = scanner2.nextDouble();
switch (operator) {
case "+":
double sum = add(num1, num2);
System.out.println("计算结果为:" + num1 + "+" + num2 + "=" + sum);
break;
case "-":
double sub = sub(num1, num2);
System.out.println("计算结果为:" + num1 + "-" + num2 + "=" + sub);
break;
case "*":
double mul = mul(num1, num2);
System.out.println("计算结果为:" + num1 + "*" + num2 + "=" + mul);
break;
case "/":
double div = div(num1, num2);
System.out.println("计算结果为:" + num1 + "/" + num2 + "=" + div);
break;
default:
System.out.println("请输入正确的运算符!!");
}
}
//加法
public static double add(double i, double j) {
return i + j;
}
//减法
public static double sub(double i, double j) {
return i - j;
}
//乘法
public static double mul(double i, double j) {
return i * j;
}
public static double div(double i, double j) {
if (j == 0) {
System.out.println("计算不合法!!!!");
}
return i / j;
}
}
借鉴博主Aynaner