-3

When I print an instance of my class, the instance is referenced as "null" because I return "null", how can I format the toString class so it will return what I actually wrote in this function:

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

For example, it has to return "m1 = 13a^2b^3" (it is a polynom) but instead is returns "13a^2b^3 m1 = null"

Ilan Aizelman WS
  • 1,630
  • 2
  • 21
  • 44
  • Well, don't print anything. Instead; concatenate the parts you want to return and return the result. Returning and printing are very different things. – JB Nizet Apr 29 '17 at 19:05
  • Read [this](http://stackoverflow.com/questions/3615721/how-to-use-the-tostring-method-in-java) – Robin Topper Apr 29 '17 at 19:07

2 Answers2

1

Instead of directly printing each component of the String, concatenate them by using a StringBuilder:

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();
}
Gooz
  • 1,106
  • 2
  • 9
  • 20
-1

Use String Builder . Wherever you are using System.out.println

Instead of that

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

       // at the end 
        return temp.toString();
Vikrant
  • 178
  • 4