...

View Full Version : array toString



codefreaq
04-20-2008, 12:20 AM
I am getting an error (toString cannot override Java toString) when compiling this. its probably something really dumb since i am just starting on java. can someone help plz




public class Temperature

{
/* Instance variables*/
private int [] weekTemps = new int [7];
private int i,z;

/* constructor */

public Temperature(int [] startWeekTemps)
{
for(i=0;i<7;i++)
{
weekTemps[i]=startWeekTemps[i];
}
}

/* accessor */

public int[] getWeekTemps()
{
return weekTemps;
}

/* mutator */

public void setWeekTemps(int [] newWeekTemps)
{
for(i=0;i<z;i++)
{
weekTemps[i]=newWeekTemps[i];
}
}

/* equals method */

public boolean equals(Object Temperature)
{
for(i=0;i<7;i++)
{
if (weekTemps[i] == weekTemps[i])
{return true;}
else
{return false;}
}
}

/* tostring method */
public int[] toString()
{
return(weekTemps[])
}




}

tagnu
04-20-2008, 05:17 AM
i'm not a Java wiz, but I guess your code's trying to override the method toString() in java,
try renaming your function to some other name.. like toStringfunction() :)

Aradon
04-20-2008, 10:12 PM
Please post the compile errors you are getting in the future.

The above poster is right and wrong (I suppose a consequence of not being a java guy :P )



/* tostring method */
public int[] toString()
{
return(weekTemps[])
}


You basically can't do this. (You don't even have a ; at the end of the statement either).

The toString method always returns a String first off. With that, when you write a toString method what you want to do is go through each array element, concatenate that element to an already created string (initially empty), and then return that String.

Also



public boolean equals(Object Temperature)
{
for(i=0;i<7;i++)
{
if (weekTemps[i] == weekTemps[i])
{return true;}
else
{return false;}
}
}


That isn't doing what you probably think it's doing. According to your code, it will always return true.

Why do I know this? Because you're comparing the same thing to itself! So of course it's true. What you want to compare is the weekTemps with the Object that is passed in (presumably the same object type that weekTemps is apart of).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum