我正在制作一个简单的计算器,但是在我能够做到这一点之前,我需要制作一个算法来将用户输入转换为一致的格式。用户可以输入数字和运算符以及括号。该程序处理数字和运算符没有问题,但由于某些未知原因,只要循环遇到括号,它就会抛出错误。
我一直在尝试调试过去几个小时的代码,但我似乎无法弄清楚为什么会发生这种情况?
/** These are the possible operators */
private static final String OPERATORS = "+-/*%^()[]{}";
/** This is an ArrayList of all the discrete
things (operators/operands) making up an input.
This is really just getting rid of the spaces,
and dividing up the "stuff" into manageable pieces.
*/
static ArrayList<String> input = new ArrayList<String>();
public static ArrayList inputCleaner(String postfix) {
StringBuilder poop = new StringBuilder();
String doody = postfix.replace(" ", "");
try {
for (int i = 0; i < doody.length(); i++) {
char c = doody.charAt(i);
boolean isNum = (c >= '0' && c <= '9');
if (isNum) {
poop.append(c);
if (i == doody.length() - 1) {
input.add(poop.toString());
poop.delete(0, poop.length());
}
}
else if (c == '.') {
for (int j = 0; j < poop.length(); j++) {
if (poop.charAt(j) == '.') {
throw new SyntaxErrorException("You can't have two decimals in a number.");
}
else if (j == poop.length() - 1) {
poop.append(c);
}
}
if (i == doody.length() - 1) {
throw new SyntaxErrorException("You can't end your equation with a decimal!");
}
}
else if (OPERATORS.indexOf(c) != -1 && poop.length() != 0) {
input.add(poop.toString());
poop.delete(0, poop.length());
poop.append(c);
input.add(poop.toString());
poop.delete(0, poop.length());
}
else {
throw new SyntaxErrorException("Make sure your input only contains numbers, operators, or parantheses/brackets/braces.");
}
}
return input;
}
catch (SyntaxErrorException exc) {
System.out.println("That didn't work, something was wrong with the syntax.");
return input;
}
}
public static void main(String[] args) {
ArrayList test = new ArrayList();
Scanner f = new Scanner(System.in);
System.out.println("Please insert an argument: \n");
String g = f.nextLine();
test = inputCleaner(g);
for (int z = 0; z < test.size(); z++) {
System.out.println(test.get(z));
}
}
答案 0 :(得分:0)
我知道我的答案不是很好因为我对它没有很好的解释(由于工作中的大脑过热)但这种变化不会像你的情况那样抛出异常(可能是你的答案;))< / p>
我没有在条件中使用poop.length() != 0
,而只是将其更改为poop != null
而瞧...现在没有Exceptions
。评论你是否可以解释我这个。