跟着狂神学java,p50计算器实现源码,仅代表个人,不足之处,欢迎指正,谢谢
作者:互联网
package com.kuang.Method;
import java.util.Scanner;
public class Demo08 {
public static void main(String[] args) {
String start = "s";
String end = "e";
String str = "0";
String operator = "0";
double result = 0;
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("输入s以开始计算,或输入e以结束计算:");
str = scanner.next();
if (str.equals(start)){
double num1 = 0;
double num2 = 0;
System.out.println("请输入num1:");
num1 = scanner.nextDouble();
do {
System.out.println("请输入要继续的指令:+、-、*、/、%、clr、e");
operator = scanner.next();
if ((operator.equals("+")) || (operator.equals("-")) || (operator.equals("*"))
|| (operator.equals("/")) || (operator.equals("%")))
{
System.out.println("请输入num2:");
num2 = scanner.nextDouble();
switch (operator){
case "+":
result = add(num1,num2);
break;
case "-":
result = sub(num1,num2);
break;
case "*":
result = mul(num1,num2);
break;
case "/":
result = div(num1,num2);
break;
case "%":
result = mod(num1,num2);
break;
}
System.out.println("运算结果为:"+num1+operator+num2+" = "+result);
System.out.println("====================================");
num1 = result;
}else if (operator.equals("clr")){
result = 0;
System.out.println("清零:"+"result" +" = "+result);
System.out.println("====================================");
System.out.println("继续请输入s,结束请输入任意");
if (scanner.next().equals("s")){
System.out.println("请输入num1:");
num1 = scanner.nextDouble();
}else {
System.out.println("计算结束");
System.out.println("====================================");
break;
}
}else if (operator.equals("e"))
{
System.out.println("计算结束");
System.out.println("====================================");
// scanner.close();不能写这里,会导致:::
// 直接break只是跳出当前do while循环,回到while循环
// 所以会回到System.out.println("输入s以开始计算,或输入e以结束计算:");
//由于scanner关闭,而又有str = scanner.next();导致错误
break;
}else {
System.out.println("您输入的运算符非预期");
}
}while (true);
}else if (str.equals(end)){
scanner.close();
System.out.println("计算结束");
System.out.println("====================================");
break;
}else {
System.out.println("输入指令非s或e,请重新输入。");
System.out.println("------------------------------------");
System.out.println("");
}
}
}
public static double add(double num1,double num2){
double addSum = num1 + num2;
return addSum;
}
public static double sub(double num1,double num2){
double subSum = num1 - num2;
return subSum;
}
public static double mul(double num1,double num2){
double mulSum = num1 * num2;
return mulSum;
}
public static double div(double num1,double num2){
double divSum = num1 / num2;
return divSum;
}
public static double mod(double num1,double num2){
double modSum = num1 % num2;
return modSum;
}
}
标签:java,num1,num2,double,System,源码,println,p50,out 来源: https://www.cnblogs.com/LND-tingyu/p/16092914.html