2014-05-05 33 views
0

我正在製作一個簡單的計算器,但是在我可以做到這一點之前,我需要制定一個算法將用戶輸入轉換爲一致的格式。用戶可以輸入數字和運算符以及括號。程序在處理數字和運算符時沒有問題,但是由於某些未知原因,當循環遇到括號時它會引發錯誤。當用戶輸入括號時,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)); 
    } 
} 
+1

你準確地捕捉到了什麼錯誤?它拋出哪條線? – sp00m

+0

拋出什麼錯誤? – PKlumpp

+0

它引發SyntaxErrorException。奇怪的部分是出現錯誤,那麼程序會將ArrayList的內容打印到括號(括號不包括在內)。只要沒有包括括號,錯誤就不會被拋出。該程序似乎與其他運算符不同的是處理括號。這就是我困惑的原因。該程序適用於 - + * /%^。 – FelixTheNub

回答

0

我知道我的答案是不是很好怎麼我自己也沒有很好的解釋(因大腦過熱的工作),但這種變化不會引發異常,因爲在你的情況(可能是你的答案;))

而不是使用poop.length() != 0在條件我已經簡單地將其更改爲poop != null和瞧...現在沒有Exceptions。評論如果你能解釋我這一點。

+0

感謝您的檢查!這個問題在我原來的帖子的評論部分得到解決。 – FelixTheNub

+0

我感謝您的關注,這是缺乏聲譽,只能說我無法在那裏發表評論。我認爲我的答案在評論和實際答案之間有所不同。我會記住你的愛心;)TY。 –

相關問題