我已经编写了一个程序,它接受输入(用户键入或通过文本文件处理),并根据找到的内容调用数学计算。调用line.isEmpty()方法时输出重复的答案
问题一旦出现答案并打印出来,每line.isEmpty()
扫描仪检测到它将重新计算并打印出以前的答案。如果有4个空行,它将被打印4次,直到将另一个问题解析到程序中。
这是我的主要方法:
public static void main(String[] args) {
Calc calc = new Calc();
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
String input = "";
List<String> strs = new ArrayList<>();
//
ArrayList<String> tokens;
//this makes sure an entire problem is added as a tokens element
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.isEmpty()) {
for (String s : strs) {
sb.append(s);
input = sb.toString();
}
tokens = new ArrayList<>(Arrays.asList(input.split(" ")));
//call calculate on strs then reset
calc.calculate(tokens);
strs.clear();
tokens.clear();
sb.setLength(0);
} else if (line.length() == 1) {
strs.add(" ");
strs.add(line);
strs.add(" ");
} else {
strs.add(line);
}
}
}
和计算方法:
public String calculate(List<String> tokens) {
operands = new Stack<>();
for (int i = 0; i < tokens.size(); i++) {
tokens.removeAll(Arrays.asList(""));
}
String result = processOperands(tokens);
if (result.equals(null)) {
System.out.println(result);
return defaultResult;
} else if (result.equals("java.lang.IllegalArgumentException: Attempting to add with fewer than 2 operands.")) {
System.out.println(result);
return "java.lang.IllegalArgumentException: Attempting to add with fewer than 2 operands.";
} else {
System.out.println(result);
return result.replaceAll("[^\\d.]", "");
}
}
对于输入:
2 2 +
4
3 +
输出:
4
4
4
7
很明显,问题在于我每次检测到一个空字符串时都会调用它,因为当前它是如何知道问题何时完成的“输入”。
我该如何修改这个要么知道不打印相同的答案两次,要么不计算答案,直到找到另一个答案?
这已经在代码中。 'calc.calculate(令牌); strs.clear(); tokens.clear(); sb.setLength(0);' – Alkarin
到目前为止,你已经做了什么来弄清楚为什么会出现问题? – immibis