请使用面向对象的程序设计方法实现一个小型计算器功能,要求输入2个

2024-11-04 09:23:45
推荐回答(2个)
回答1:

我使用Java做的:
operate.java
public class operate {
/*
操作符类,使用了封装-定义一个private类型的变量,通过public方法读写
* */
//第一个数字
private double numA;
//第二个数字
private double numB;
//操作符
private String operation;
//获取第一个的数字
public double getNumA() {
return numA;
}
//输入第一个数字
public void setNumA(double numA) {
this.numA = numA;
}
//获取第二个数字
public double getNumB() {
return numB;
}
//输入第二个数字
public void setNumB(double numB) {
this.numB = numB;
}
//获取操作符
public String getOperation() {
return operation;
}
//输入操作符
public void setOperation(String operation) {
String str = "";
//当操作符不是+、-、*、/的时候输入ERRO,否则输入操作符
if (!operation.equalsIgnoreCase("+")&&!operation.equalsIgnoreCase("-")
&&!operation.equalsIgnoreCase("*")&&!operation.equalsIgnoreCase("/")) {
str = "ERRO";
}else{
str = operation;
}
this.operation = str;
}
}
入口类:
test.java
import java.util.Scanner;
public class test {
//实例化operate类
private static operate ope = new operate() ;
//输入第一个数字
private static void InputNumA(){
try {
System.out.print("请输入第一个数字:");
ope.setNumA(new Scanner(System.in).nextDouble());
} catch (Exception e) {
System.out.println("你输入的不是数字,请重新输入!");
System.out.println(" ");
InputNumA();
}
}

//输入第二个数字
private static void InputNumB(){
try {
System.out.print("请输入第一个数字:");
ope.setNumB(new Scanner(System.in).nextDouble());
} catch (Exception e) {
System.out.println("你输入的不是数字,请重新输入!");
System.out.println(" ");
InputNumB();
}
}

//输入操作符
private static void InputOp(){
System.out.print("请输入操作符:");
ope.setOperation(new Scanner(System.in).next());
if (ope.getOperation().equalsIgnoreCase("ERRO")) {
System.out.println("你输入的操作符是错误的,请重新输入!");
System.out.println(" ");
InputOp();
}
}
public static void main(String[] args) {
double result = 0;
InputNumA();
System.out.println(" ");
InputNumB();
System.out.println(" ");
InputOp();
if (ope.getOperation().equalsIgnoreCase("+")) {
result = ope.getNumA() + ope.getNumB();
}else if (ope.getOperation().equalsIgnoreCase("-")) {
result = ope.getNumA() - ope.getNumB();
}else if (ope.getOperation().equalsIgnoreCase("*")) {
result = ope.getNumA() * ope.getNumB();
}else if (ope.getOperation().equalsIgnoreCase("/")) {
result = ope.getNumA() * 1.0 / ope.getNumB();
}
System.out.println(ope.getNumA()+" "+ ope.getOperation()
+" "+ ope.getNumB() +" = " + result);
}
}

回答2:

Private Sub Command1_Click()

a = InputBox("请输入第一个数")
b = InputBox("请输入运算符")
c = InputBox("请输入第二个数")

Select Case b
Case "+"
MsgBox Val(a) + Val(c)
Case "-"
MsgBox Val(a) - Val(c)
Case "*"
MsgBox Val(a) * Val(c)

Case "/"
MsgBox Val(a) / Val(c)
End Select

End Sub