public static void main(String[] args) { Scanner sc = new Scanner(System.in); String [] ops = sc.nextLine().split(" "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ops.length; i++) { ops[i]=sc.nextLine(); if (ops[i]=="[0-9]"){ sb.append(ops[i]); }else if (ops[i]=="+"){ sb.append((ops[i-1]+ops[i-2])); }else if (ops[i]=="C"){ sb.deleteCharAt(i-1); }else if (ops[i]=="D"){ sb.append((ops[i-1]+ops[i-1])); }else { System.out.println("-1"); } System.out.println(sb.toString()); } };检查上面的代码,标出问题,并且优化下代码输出
时间: 2024-02-14 15:09:35 浏览: 118
在这个程序中,有以下两个问题:
1. 字符串比较应该使用equals方法,而不是==运算符。
2. 在处理加法、撤销和双倍运算时,应该先检查是否存在足够的操作数。
下面是修复了这些问题的代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ops = sc.nextLine().split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ops.length; i++) {
if (ops[i].matches("[0-9]+")) {
sb.append(ops[i]);
} else if (ops[i].equals("+")) {
if (sb.length() < 2) {
System.out.println("-1");
return;
}
int a = Integer.parseInt(sb.substring(sb.length() - 2, sb.length() - 1));
int b = Integer.parseInt(sb.substring(sb.length() - 1));
sb.append(a + b);
} else if (ops[i].equals("C")) {
if (sb.length() < 1) {
System.out.println("-1");
return;
}
sb.deleteCharAt(sb.length() - 1);
} else if (ops[i].equals("D")) {
if (sb.length() < 1) {
System.out.println("-1");
return;
}
int a = Integer.parseInt(sb.substring(sb.length() - 1));
sb.append(a * 2);
} else {
System.out.println("-1");
return;
}
System.out.println(sb.toString());
}
}
}
```
优化输出:
在每次处理完操作后,输出当前的得分情况即可,不需要每次都输出所有的操作序列。修改后的代码如下:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ops = sc.nextLine().split(" ");
StringBuilder sb = new StringBuilder();
int sum = 0;
for (int i = 0; i < ops.length; i++) {
if (ops[i].matches("[0-9]+")) {
sb.append(ops[i]);
sum += Integer.parseInt(ops[i]);
} else if (ops[i].equals("+")) {
if (sb.length() < 2) {
System.out.println("-1");
return;
}
int a = Integer.parseInt(sb.substring(sb.length() - 2, sb.length() - 1));
int b = Integer.parseInt(sb.substring(sb.length() - 1));
sb.append(a + b);
sum += a + b;
} else if (ops[i].equals("C")) {
if (sb.length() < 1) {
System.out.println("-1");
return;
}
sum -= Integer.parseInt(sb.substring(sb.length() - 1));
sb.deleteCharAt(sb.length() - 1);
} else if (ops[i].equals("D")) {
if (sb.length() < 1) {
System.out.println("-1");
return;
}
int a = Integer.parseInt(sb.substring(sb.length() - 1));
sb.append(a * 2);
sum += a * 2;
} else {
System.out.println("-1");
return;
}
System.out.println(sum);
}
}
}
```
阅读全文