帮我写一个java代码,要求如下:小牛刚学C语言,他总是对C语言关系运算搞不清楚,现在请你帮他设计一个程序,完成一个由整数和关系运算组成的表达式的结果。 如3<5<10,该关系表达式结果为1,而-10<20!=9>3,该关系表达式结果为0。 输入格式 包括两部分。 第一部分:一个整数N(1<=N<=100),代表有N组测试。 第二部分:由N行组成。每行对应一个测试,由非负整数和C语言关系运算符组成的关系表达式,长度小于100。 输出格式 每行关系表达式的执行结果 样例输入 4 3<5<10 10<20!=9>3 1==0 12<53!=1>0<=181 样例输出 1 0 0 0
时间: 2024-02-12 19:07:11 浏览: 28
以下是符合要求的 Java 代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine(); // 读取换行符
for (int i = 0; i < n; i++) {
String expression = scanner.nextLine();
String[] tokens = expression.split("\\s+"); // 使用正则表达式分割表达式
int a = Integer.parseInt(tokens[0]);
boolean result = true;
for (int j = 1; j < tokens.length - 1; j += 2) {
String operator = tokens[j];
int b = Integer.parseInt(tokens[j + 1]);
if (operator.equals("<")) {
result = a < b;
} else if (operator.equals("<=")) {
result = a <= b;
} else if (operator.equals(">")) {
result = a > b;
} else if (operator.equals(">=")) {
result = a >= b;
} else if (operator.equals("==")) {
result = a == b;
} else if (operator.equals("!=")) {
result = a != b;
}
if (!result) {
break;
}
a = b;
}
if (result) {
System.out.println(1);
} else {
System.out.println(0);
}
}
scanner.close();
}
}
```
代码实现的思路是:首先读入测试数据的数量 `n`,然后循环读入每个测试数据。对于每个测试数据,我们将其按照空格分割,得到一个字符串数组 `tokens`,其中每个元素都是一个整数或关系运算符。接着,我们从左到右遍历 `tokens` 数组,依次执行每个关系运算,并保存中间结果。如果有任何一个关系运算的结果为 `false`,那么整个表达式的结果就为 `false`。最后,根据表达式的结果输出 `1` 或 `0`。
希望这个代码能够帮助到您。如果您有任何问题,请随时问我。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)