Java 如何使用数组返回String.format

Java 如何使用数组返回String.format,java,tostring,Java,Tostring,当我打印我的类的实例时,该实例被引用为“null”,因为我返回“null”,如何格式化toString类,使其返回我在该函数中实际编写的内容: public String toString() { System.out.print(this.coefficient); for(int i=0; i<26;i++) { if(degrees[i] == 1) { System.out.print(variable

当我打印我的类的实例时,该实例被引用为“null”,因为我返回“null”,如何格式化toString类,使其返回我在该函数中实际编写的内容:

public String toString()
{
    System.out.print(this.coefficient);
    for(int i=0; i<26;i++)
    {
        if(degrees[i] == 1)
        {
            System.out.print(variables[i]);
        }
        if(degrees[i]>1)
        {
            System.out.print(variables[i] + "^" + degrees[i]);
        }
    }
    System.out.println('\n');
    return null;
}
公共字符串toString()
{
系统输出打印(该系数);
对于(int i=0;i1)
{
系统输出打印(变量[i]+“^”+度[i]);
}
}
System.out.println('\n');
返回null;
}
例如,它必须返回
“m1=13a^2b^3”
(它是一个多项式)
而是返回
“13a^2b^3 m1=null”

而不是直接打印
字符串的每个组件,使用
字符串生成器将它们连接起来:

public String toString()
{
    StringBuilder s = new StringBuilder();

    s.append(this.coefficient);
    for (int i = 0; i < 26; i++)
    {
        if (degrees[i] == 1)
        {
            s.append(variables[i]);
        }
        else if (degrees[i] > 1)
        {
            s.append(variables[i]).append('^').append(degrees[i]);
        }
    }

    return s.toString();
}
公共字符串toString()
{
StringBuilder s=新的StringBuilder();
s、 附加(该系数);
对于(int i=0;i<26;i++)
{
如果(度[i]==1)
{
s、 追加(变量[i]);
}
如果(度数[i]>1),则为else
{
s、 追加(变量[i])。追加('^')。追加(度[i]);
}
}
返回s.toString();
}
使用字符串生成器。 无论您在何处使用System.out.println

相反

      StringBuilder temp=new StringBuilder();
      temp.append();// Add here the content what you are printing with Sysout 

       // at the end 
        return temp.toString();

好吧,不要打印任何东西。相反连接要返回的部分并返回结果。返回和打印是完全不同的事情。阅读