Java循环实现计算器连续加减乘除
时间: 2024-10-25 17:14:56 浏览: 22
Java计算器源码 JavaJisuanqi.rar
在Java中,我们可以使用while或do-while循环来实现一个简单的计算器,让用户可以连续输入加、减、乘、除操作。下面是一个基本的例子:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1 = 0, result = 0;
char operator;
System.out.println("请输入第一个数字:");
num1 = scanner.nextDouble();
while (true) {
System.out.println("\n请选择操作 (+, -, *, /): ");
operator = scanner.next().charAt(0);
switch (operator) {
case '+':
System.out.println("请输入第二个数:");
double num2 = scanner.nextDouble();
result = num1 + num2;
System.out.println("结果是:" + result);
num1 = result; // 更新num1以便下一次运算
break;
case '-':
System.out.println("请输入第二个数:");
num2 = scanner.nextDouble();
result = num1 - num2;
System.out.println("结果是:" + result);
num1 = result;
break;
case '*':
System.out.println("请输入第二个数:");
num2 = scanner.nextDouble();
result = num1 * num2;
System.out.println("结果是:" + result);
num1 = result;
break;
case '/':
if (num2 != 0) { // 防止除数为零
System.out.println("请输入第二个数:");
num2 = scanner.nextDouble();
result = num1 / num2;
System.out.println("结果是:" + result);
num1 = result;
} else {
System.out.println("错误!除数不能为零。");
}
break;
default:
System.out.println("无效的操作符,请重新选择。");
}
System.out.print("是否继续计算?(y/n)");
String continueChoice = scanner.next().toLowerCase();
if (!continueChoice.equals("y")) {
break; // 用户选择退出,则跳出循环
}
}
scanner.close();
}
}
```
阅读全文