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"
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();
}
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();