use Java to design a working calculator
时间: 2024-04-12 08:28:13 浏览: 14
Sure! I can help you with that. Here's a basic implementation of a calculator in Java:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
System.out.println("Result: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error: Division by zero is not allowed.");
}
break;
default:
System.out.println("Error: Invalid operator.");
break;
}
scanner.close();
}
}
```
This calculator program prompts the user to enter two numbers and an operator (+, -, *, /). It then performs the corresponding operation and displays the result. Note that division by zero is not allowed.
You can compile and run this program to use the calculator functionality. Let me know if you have any further questions!