How can a calculator be implemented in Java to perform addition, subtraction, multiplication, and division?
Here is a simple example code in Java for a calculator that performs addition, subtraction, multiplication, and division.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.print("请输入运算符(+、-、*、/):");
String operator = scanner.next();
System.out.print("请输入第二个数字:");
double num2 = scanner.nextDouble();
double result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("除数不能为0");
return;
}
break;
default:
System.out.println("不支持的运算符");
return;
}
System.out.println("计算结果:" + result);
}
}
After running the above code, the program will prompt the user to input two numbers and an operator (+, -, *, /), and then perform the corresponding calculation based on the operator, and output the result.
Please note that the above code is just a simple example with no input validation and exception handling, only capable of performing basic arithmetic operations. In real-world applications, it may be necessary to implement stricter input validation and handle various possible exceptions.