2013-11-26 62 views
2

這是一個toString方法,用於格式化多項式的項並將它們添加到字符串中。它的最終輸出就像是「+ 2x^2 + 2x + 1」。我會如何去除第一個加號?由於toString方法多項式

//toString method for returning ReesePolynomials in polynomaial format(for ReeseClient) 
     public String toString() 
     { 
      String output = ""; 
      //the following are situations for formatting the output of each term and adding them to String output 
      for (int i = 0; i < TermLength; i++) // For the number of terms stated by the user earlier, values will be given for each ReeseTerm in the poly array 
      { 
       if (poly[i].getExpo() == 0 && poly[i].getCoeff() > 0)  
       { 
        output += " + " + poly[i].getCoeff(); 
       } 

       else if (poly[i].getExpo() == 0 && poly[i].getCoeff() < 0) 
       { 
        output += " " + poly[i].getCoeff(); 
       } 

       else if (poly[i].getCoeff() == 1 && (poly[i].getExpo() != 0 && poly[i].getExpo() != 1)) 
       { 
        output += " + x^" + poly[i].getExpo(); 
       } 

       else if (poly[i].getCoeff() == 1 && (poly[i].getExpo() == 1)) 
       { 
        output += " + x";  
       } 

       else if (poly[i].getExpo() == 1 && poly[i].getCoeff() > 0) 
       { 
        output += " + " + poly[i].getCoeff() + "x"; 
       } 

       else if (poly[i].getExpo() == 1 && poly[i].getCoeff() < 0) 
       { 
        output += " " + poly[i].getCoeff() + "x"; 
       } 

       else if (poly[i].getCoeff() < 0 && (poly[i].getExpo() > 1 || poly[i].getExpo() < -1)) 
       { 
        output += " " + poly[i].getCoeff() + "x^" + poly[i].getExpo(); 
       } 

       else if (poly[i].getCoeff() == 0) 
       {} 

       else 
       { 
        output += " + " + poly[i].getCoeff() + "x^" + poly[i].getExpo(); 
       } 

      } 

     return output;  // the final string output is returned to be printed when called upon in main 
     } 
+0

不要把它放在那裏擺在首位。 – EJP

+0

除了在極少數情況下(例如,遞歸瀏覽列表並將其打印到控制檯或某些類別時)之外,這比固定fencepost問題困難得多。 –

+0

@BigEndian我不同意。不犯錯誤比在完成之後修復它要簡單得多。 – EJP

回答

1

嘗試
output = output.subString(2);
return output;