我的代码如下所示:
private static String getShoppingLine()
{
for(int index = 0; index <= ProductInfoName.length; index++)
{
return ProductInfoName[index];
}
}
但它声明在最后有一个return语句会出错。但我已经在循环中有一个。请指教。感谢。
答案 0 :(得分:0)
private static String getShoppingLine()
{
for(int index = 0; index <= ProductInfoName.length; index++)
{
return ProductInfoName[index]; // don't do this.
}
return null; //add here too
}
而不是在内部写return
语句,for-loop
将其写在外面。因为,控件将返回ProductInfoName[0]
。
注意:必须在方法中找到您的return
语句(如果您已经为方法声明了任何返回类型)。因为,无法保证您的for-loop
始终执行。然后,在这种情况下,您的方法将不会返回任何内容。因此,您需要在return
之外添加一个for-loop
语句。
答案 1 :(得分:0)
当然可以。 ProductInfoName.length
可能是否定的。如果它是否定的,那么您的return
语句将无法执行。
注意:当然实际上它可能是否定的,但编译器在编译代码时并不知道。
第二个注意事项:这不是编写此方法的方法。你总是返回数组中的第一个元素(如果它不存在,你将会抛出异常)。您应该用以下代码替换您的代码:
private static ...
{
if(ProductInfoName.length>0)
return ProductInfoName[0];
return null;
}
答案 2 :(得分:0)
您将始终返回ProductInfoName [0], 你为什么不写回归productinfoname [0]? 如果数组中根本没有对象怎么办?
答案 3 :(得分:0)
您没有在代码中返回任何内容。
如果要将最后一个值更改返回到下面给出的代码
private static String getShoppingLine()
{
String str="";
for(int index = 0; index <= ProductInfoName.length; index++)
{
str=ProductInfoName[index];
}
return str;
}