利用Java写一个计算器,用户可以自己输入数据,在输入错误信息时提示用户重新输入
时间: 2024-04-30 20:23:05 浏览: 43
以下是一个简单的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;
String operator;
System.out.print("Enter first number: ");
while (!input.hasNextDouble()) {
System.out.print("Invalid input. Please enter a valid number: ");
input.next();
}
num1 = input.nextDouble();
System.out.print("Enter second number: ");
while (!input.hasNextDouble()) {
System.out.print("Invalid input. Please enter a valid number: ");
input.next();
}
num2 = input.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
operator = input.next();
while (!operator.matches("[+\\-*/]")) {
System.out.print("Invalid input. Please enter a valid operator (+, -, *, /): ");
operator = input.next();
}
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
System.out.println("Division by zero is not allowed.");
return;
}
result = num1 / num2;
break;
default:
System.out.println("Invalid operator.");
return;
}
System.out.println("Result: " + result);
}
}
```
代码中的正则表达式`[+\\-*/]`用于验证操作符是否为+、-、*或/。如果不是,则提示用户重新输入。
阅读全文