2015-12-17 46 views
0

瘋狂的長但必要的介紹: 現在,我正在寫一個綜合的分部計算器。要做到這一點,有幾個步驟(讓計算機做到這一點)。 我已經做一步一個解析插入的java因子列表

  1. 輸入必須是(比方說3x^2+2x^1+3x^0)解析成每個術語的片段(如3x^22x^1等)
  2. 接着,將各系數必須被添加到數組或具有度數元素的數組列表。如果您熟悉合成分工,您知道這些因素必須按照它們的匹配程度排序(3x^2 + 2x^1 + 0x^1必須以3,2,0的形式進入)。另外,如果缺少某種程度,則應該添加數字零。例如,如果輸入是3x^2 + 2x^0,則必須在中間添加零,因爲缺少等級爲1的項。輸出將是3,0,2

我做了什麼來解決這個問題:

如果我還沒有說這個,我用Java編寫。 (請注意:我想在這裏創造一個MVC也希望看到完整的代碼,請here

//Cycle through all the degrees 
for (int i = this.degree; i>=0; i--){ 
     //We can set a boolean value on 
     //whether we have found the term in the array with the correct degree 
     boolean found = false; 

     // arr is the array with all the terms (2x^2) etc. 
     for (String each : arr){ 
      //checks if the current term is of the degree we are looking for (i) 
      if(lookForTheTerm(each,i)){ 
       try{ 
       //Add it to the resulting array list 
       coefficients.add(getCoeffFromString(arr[i])); 
       } 
       catch (Exception e){ 

       } 
       //We found it 
       found = true; 
       //Break out of the loop (if we found it, we don't need to keep looking) 
       break; 
      }   

     } 
     //If we didn't find it, add a 0 to the array list 
     if(!found){ 
      coefficients.add((float) 0); 
     } 

    } 
    //Not shown: After iterating, reverse the list to be correct 

的問題:

此代碼的工作,如果所有的條款在那裏。含義3x^2+1x^1+0x^0(有一個2,1和0的術語)。

如果它們出現故障,它會做一些完全瘋狂的事情。

如果有人失蹤並且他們按順序存在,它將置入零,但忽略主要術語。

代碼有什麼問題?我幾乎肯定它是一個語義錯誤。我再次嘗試提供MVC。但如果這是不夠的,完整的代碼可以看出here.

感謝先進

+0

你有很多使用split()的文本處理。你嘗試調試放入數組中的術語嗎? –

+0

是的,這些術語都是正確分割的。 @JohnScattergood – intboolstring

+0

我想我明白了。 –

回答

0

問題1的幫助:訂購

您正在分析從第一項的程度,然後使用循環通過條款的程度。如果你先把第二學位,那麼它只會處理2學期。

您可以通過首先按照學位排序來解決此問題。

問題2:更少項

這是通過與學位相關的問題引起的,但糟糕的是:

coefficients.add(getCoeffFromString(arr[i])); 
      } 
      catch (Exception e){ 

      } 

,你正在吃的例外。如果你有2個學期,但是有3個學位,那麼在索引i處取消引用列表將會拋出一個超出界限的例外。