用Java写一个计算器界面
时间: 2024-12-28 07:30:48 浏览: 3
在Java中编写一个简单的命令行计算器界面,我们可以使用控制台输入输出来模拟。首先,创建一个Calculator类,包含加、减、乘、除等基本运算方法。下面是一个简化的示例:
```java
import java.util.Scanner;
class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}
public int subtract(int num1, int num2) {
return num1 - num2;
}
public int multiply(int num1, int num2) {
return num1 * num2;
}
public double divide(int num1, int num2) throws ArithmeticException {
if (num2 != 0) {
return (double) num1 / num2;
} else {
throw new ArithmeticException("Cannot divide by zero");
}
}
}
public class CalculatorInterface {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calculator = new Calculator();
System.out.println("Simple Calculator:");
while (true) {
System.out.print("Enter an operation (+, -, *, /), or 'quit' to exit: ");
String op = scanner.nextLine();
if (op.equalsIgnoreCase("quit")) {
break;
}
System.out.print("Enter two numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
try {
switch (op) {
case "+":
System.out.println(num1 + " + " + num2 + " = " + calculator.add(num1, num2));
break;
case "-":
System.out.println(num1 + " - " + num2 + " = " + calculator.subtract(num1, num2));
break;
case "*":
System.out.println(num1 + " * " + num2 + " = " + calculator.multiply(num1, num2));
break;
case "/":
System.out.println(num1 + " / " + num2 + " = " + calculator.divide(num1, num2));
break;
default:
System.out.println("Invalid operation");
}
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
scanner.close();
}
}
```
在这个例子中,用户通过控制台输入操作符和数字,程序会调用Calculator类的方法进行计算。
阅读全文