练习:计算器
写一个计算器,要求实现加减乘除功能,并且能够循环接收新的数据,通过用户交互实现。
package com.yanseyutou.method;
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String isContinue = "y";
while(isContinue.equals("y")) {
double i1 = 0;//第一个数
double i2 = 0;//第二个数
String ca = "+";//运算符
double result = 0;//结果
System.out.println("请输入第一个数:");
i1 = scanner.nextDouble();
System.out.println("请输入运算符:");
ca = scanner.next();
System.out.println("请输入第二个数:");
i2 = scanner.nextDouble();
switch (ca) {
case "+":
result = add(i1, i2);
System.out.println(i1 + ca + i2 + "计算结果为:" + result);
break;
case "-":
result = sub(i1, i2);
System.out.println(i1 + ca + i2 + "计算结果为:" + result);
break;
case "*":
result = mul(i1, i2);
System.out.println(i1 + ca + i2 + "计算结果为:" + result);
break;
case "/":
if (i2 == 0) {
System.out.println("分母不可为零");
} else {
result = div(i1, i2);
System.out.println(i1 + ca + i2 + "计算结果为:" + result);
}
break;
default:
System.out.println("运算符输入错误");
}
System.out.println("进入下一次运算请输入y(不进入请随意输入):");
isContinue = scanner.next();
}
scanner.close();
}
public static double add(double i1,double i2){
return i1+i2;
}
public static double sub(double i1,double i2){
return i1-i2;
}
public static double mul(double i1,double i2){
return i1*i2;
}
public static double div(double i1,double i2){
return i1/i2;
}
}