【问题标题】:toString method for polynomials多项式的 toString 方法
【发布时间】:2013-12-12 04:44:19
【问题描述】:

这是一个 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
       }

【问题讨论】:

  • 一开始就不要放在那里。
  • 这比事后修复栅栏问题要困难得多,除非在极少数情况下(例如递归遍历列表并将其打印到控制台等)。
  • @BigEndian 我不同意。不犯错比犯错后改正要简单得多。

标签: java tostring fencepost


【解决方案1】:

试试
output = output.subString(2);
return output;

【讨论】:

    【解决方案2】:

    在你的 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

    【讨论】:

      猜你喜欢
      • 2015-12-12
      • 2016-07-21
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      相关资源
      最近更新 更多