错误代码:此方法必须 return String 类型的结果 && 在 toString 方法的 for 循环中的死代码

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

这是 toString 方法。 groceries[] 是 Geoceries 类型,长度为 6,之前已经赋值。有两个错误。一个是关于 return 类型字符串的结果,这是我做的,第二个错误是 n++ 是死代码。我想return杂货[1],杂货[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;
        }
    }

}

我建议您将代码更改为

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

    return Arrays.toString (groceries);

或者如果你真的想循环,那么你将需要附加每个项目

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

还有其他方法。