java做个简易计算器
时间: 2024-06-14 09:02:34 浏览: 106
在Java中,创建一个简易计算器可以通过控制台输入和基本的算术运算实现。以下是一个简单的步骤和代码示例:
1. 首先,定义一个Calculator类,包含两个方法:`add`用于加法,`subtract`用于减法,`multiply`用于乘法,`divide`用于除法。
```java
public class Calculator {
public double add(double num1, double num2) {
return num1 + num2;
}
public double subtract(double num1, double num2) {
return num1 - num2;
}
public double multiply(double num1, double num2) {
return num1 * num2;
}
public double divide(double num1, double num2) throws ArithmeticException {
if (num2 != 0) {
return num1 / num2;
} else {
throw new ArithmeticException("Division by zero is not allowed.");
}
}
}
```
2. 接着,创建一个`main`方法来获取用户的输入,并调用Calculator类的方法进行计算。
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calculator = new Calculator();
System.out.println("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.println("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.println("Enter an operator (+, -, *, /): ");
String operator = scanner.next();
double result;
switch (operator) {
case "+":
result = calculator.add(num1, num2);
break;
case "-":
result = calculator.subtract(num1, num2);
break;
case "*":
result = calculator.multiply(num1, num2);
break;
case "/":
result = calculator.divide(num1, num2);
break;
default:
System.out.println("Invalid operator. Please try again.");
return;
}
System.out.printf("Result: %.2f\n", result);
scanner.close();
}
}
```
阅读全文