Search code examples
javacomputer-science

Error Codes: This method must return a result of type String && dead code in a for loop within the toString method


This is the toString method. groceries[] is Type Geoceries, length of 6, values have been assigned eariler. There are two mistakes. One is on return a result of type String, which I did, second mistake is n++ is dead code. What should I do if I want to return information of groceries[1], groceries[2],...

public String toString()//Error:This method must return a result of type String
{
    
    if(groceries==null)
    {   
        return "No Groceries";
    }
    else
    {
        for(int n=0; n<groceries.length; n++)//n++ is dead code
        {   String str=groceries[n].toString();//this toString is from Groceries Class
            return str;
        }
    }

}

Solution

  • I suggest that you change your code to

    public String toString()
    {
        
        if(groceries==null)
        {   
            return "No Groceries";
        }
    
        return Arrays.toString (groceries);
    

    Or if you really want to loop, then you will ned to appended each item

    StringBuilder rv = new StringBuilder ();
    else
    {
        for(int n=0; n<groceries.length; n++)
        {   
            String str=groceries[n].toString();
            rv.append (str);
            rv.append (",");
        }
    }
    return rv.toString ();
    

    There are other ways as well.