作业
- 写一个计算器,要求实现加减乘除功能,并且能够循环接受数据,通过用户交互实现。
- 思路推荐:
- 写四个方法:加减乘除
- 利用循环+switch
- 传递需要操作两个数
- 输出结果
package com.kuang.method;
import java.util.Scanner;
public class CalcDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String isNext = "y";
while (isNext.equals("y")){
double i1 = 0;
double i2 = 0;
double result = 0;
String oper = "+";
System.out.println("请输入你的第一个数:" );
i1 = scanner.nextDouble();
System.out.println("请输入你的运算符:");
oper = scanner.next();
System.out.println("请输入你的第二个数");
i2 = scanner.nextDouble();
switch (oper){
case "+":
System.out.println("你选择"+oper+"运算符:");
result = add(i1,i2);
System.out.println("结果为"+i1+oper+i2+"="+result);
break;
case "-":
System.out.println("你选择"+oper+"运算符:");
result = min(i1,i2);
System.out.println("结果为"+i1+oper+i2+"="+result);
break;
case "*":
System.out.println("你选择"+oper+"运算符:");
result = mul(i1,i2);
System.out.println("结果为"+i1+oper+i2+"="+result);
break;
case "/":
if (i2 == 0){
System.out.println("除数不能为0!");
}else{
System.out.println("你选择"+oper+"运算符:");
result = div(i1,i2);
System.out.println("结果为"+i1+oper+i2+"="+result);
}
break;
default:
System.out.println("输入运算符错误!");
break;
}
System.out.println("是否继续计算?(输入y继续,其他任意键结束!)");
isNext = scanner.next();
}
System.out.println("感谢使用本计算器!");
scanner.close();
}
public static double add(double a,double b) {
return a+b;
}
public static double min(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;
}
}