public class Calculate {
/** * @param args */ public Double add(Double num1, Double num2){ return num1 += num2; } public Double reduce(Double num1, Double num2){ return num1 -= num2; }
public Double multip(Double num1, Double num2){ return num1 *= num2; } public Double division(Double num1, Double num2){ if(num2 == 0){ System.out.println ("error"); } return num1 /= num2; } }
|
import java.util.Scanner;
public class TestCalculate {
public static void main(String[] args) { Calculate js = new Calculate(); System.out.println("欢迎使用简单加减乘除"); String record =""; while(true) { Scanner scanner = new Scanner(System.in); System.out.println("请输入第一个数字"); double s1 = scanner.nextDouble(); record += s1; System.out.println("请输入操作符"); String operator = scanner.next(); record += operator; //double s2 = 0; while(!operator.trim().equals("=")) { System.out.print("请输入第二个数字:"); double s2 = scanner.nextDouble(); record += s2; switch (operator){ case "+": js.add(s1,s2); //s1 += s2; break; case "-": js.reduce(s1,s2); //s1 -=s2; break; case "*": js.multip(s1,s2); //s1 *=s2; break; case "/": js.division(s1,s2); //s1 /=s2; break; } System.out.print("请输入操作符:"); operator = scanner.next(); record += operator; } System.out.printf("您输入的%s=%.2f\n", record,s1); System.out.print("是否继续(Y/N)"); String isContinue = scanner.next(); if(!"Y".equals(isContinue.toUpperCase())){ break; } }
} }
|