java - 多项式的 toString 方法

标签 java tostring fencepost

这是一个 toString 方法,用于格式化多项式的项并将它们添加到字符串中。它的最终输出类似于“+ 2x^2 + 2x + 1” 我将如何删除第一个加号?谢谢

//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
       }

最佳答案

在 return 语句之前,使用 substring 方法:

output = output.substring(2);

这将为您提供从索引 2 到末尾的所有字符。 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

您面临的问题通常称为栅栏问题,或差一错误。 http://en.wikipedia.org/wiki/Off-by-one_error

关于java - 多项式的 toString 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227265/

相关文章:

c++ - 将 float 四舍五入到小数点后一位,然后转换为字符串

c++ - 使用 snprintf() 的 Fencepost 条件和可移植性?

javascript - 如何在 jquery 中访问 java enum toString() 方法?

java - 控制jsp验证的选项:include tag in eclipse Kepler

java - 使用java和apache POI读取Excel中的数据

java - Jsoup - 为 POST 传递原始正文

java - 如何将 StringReader 转换为字符串?

java - For 或 While 循环跳过输入

java - 为什么这个图形对象不绘画? (我究竟做错了什么?)