我正在製作一個簡單的計算器,但是在我可以做到這一點之前,我需要制定一個算法將用戶輸入轉換爲一致的格式。用戶可以輸入數字和運算符以及括號。程序在處理數字和運算符時沒有問題,但是由於某些未知原因,當循環遇到括號時它會引發錯誤。當用戶輸入括號時,Java程序嚇壞了
我一直在試圖調試過去幾個小時的代碼,但我似乎無法弄清楚爲什麼會發生這種情況?
/** 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));
}
}
你準確地捕捉到了什麼錯誤?它拋出哪條線? – sp00m
拋出什麼錯誤? – PKlumpp
它引發SyntaxErrorException。奇怪的部分是出現錯誤,那麼程序會將ArrayList的內容打印到括號(括號不包括在內)。只要沒有包括括號,錯誤就不會被拋出。該程序似乎與其他運算符不同的是處理括號。這就是我困惑的原因。該程序適用於 - + * /%^。 – FelixTheNub