能否修改成不读取命令行改成诱导使用者输入
时间: 2023-10-09 09:11:17 浏览: 32
当然可以,下面是修改后的代码:
```
import java.util.Scanner;
public class ArithmeticT1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first operand: ");
int operand1 = 0;
try {
operand1 = Integer.parseInt(input.nextLine().trim());
} catch (NumberFormatException ex) {
System.out.println("Wrong operand input");
System.exit(1);
}
System.out.print("Enter the operator (+, -, *, /): ");
String operator = input.nextLine().trim();
if(!operator.equals("+") && !operator.equals("-") && !operator.equals("*") && !operator.equals("/")) {
System.out.println("Wrong operator input");
System.exit(1);
}
System.out.print("Enter the second operand: ");
int operand2 = 0;
try {
operand2 = Integer.parseInt(input.nextLine().trim());
} catch (NumberFormatException ex) {
System.out.println("Wrong operand input");
System.exit(1);
}
int result = 0;
switch (operator) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
if (operand2 == 0) {
System.out.println("Cannot divide by zero");
System.exit(1);
}
result = operand1 / operand2;
break;
}
System.out.println(operand1 + " " + operator + " " + operand2 + " = " + result);
}
}
```
这个程序使用Scanner类从用户那里读取输入。它首先提示用户输入第一个操作数,然后尝试将输入解析为整数。如果用户输入的不是整数,则显示错误消息并退出程序。程序然后提示用户输入运算符。如果用户输入的运算符不是有效的运算符,则显示错误消息并退出程序。程序然后提示用户输入第二个操作数,尝试将输入解析为整数。如果用户输入的不是整数,则显示错误消息并退出程序。最后,程序执行相应的算术运算,并显示算术表达式和结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)