java计算器综合程序
时间: 2023-11-21 18:01:17 浏览: 91
以下是一个简单的Java计算器综合程序,可以进行基本的加减乘除运算和清零操作。
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.print("Enter the first number: ");
num1 = input.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
operator = input.next().charAt(0);
System.out.print("Enter the second number: ");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case '-':
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case '*':
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case '/':
if (num2 == 0) {
System.out.println("Error: division by zero");
} else {
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
}
break;
default:
System.out.println("Invalid operator");
break;
}
input.close();
}
}
```
这个程序要求用户输入两个数字和一个运算符,然后根据运算符执行相应的计算,并输出结果。如果输入的运算符不是加、减、乘或除,则输出“Invalid operator”。如果进行除法运算时除数为零,则输出“Error: division by zero”。用户可以重复执行这个计算器程序,直到退出程序。
阅读全文