从键盘输入一个只有加减运算的表达式(以回车键响应输入),例如:12-3+9,计算该表达式的值,并将计算的结果输出到文本文档(test3.txt)。本题的Java程序命名为test3。
时间: 2024-03-22 07:38:29 浏览: 38
以下是Java程序test3的代码实现:
```java
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
public class test3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String expr = sc.nextLine();
sc.close();
int result = calculate(expr);
System.out.println(result);
try {
FileWriter writer = new FileWriter("test3.txt");
writer.write(Integer.toString(result));
writer.close();
} catch (IOException e) {
System.out.println("Error writing to file.");
}
}
public static int calculate(String expr) {
int result = 0;
int num = 0;
char op = '+';
for (int i = 0; i < expr.length(); i++) {
char c = expr.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
}
if ((!Character.isDigit(c) && c != ' ') || i == expr.length() - 1) {
if (op == '+') {
result += num;
} else if (op == '-') {
result -= num;
}
op = c;
num = 0;
}
}
return result;
}
}
```
程序先从键盘输入一个只有加减运算的表达式,然后调用calculate函数计算表达式的值。计算过程中,程序通过循环遍历表达式中的每个字符,将数字字符转换成数字,运算符则根据上一个运算符来确定运算方式。最后,程序将计算的结果输出到控制台,并将结果写入文本文档test3.txt中。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)