在java语言里for循环里的变量如何声明在外面进行使用。

public TProduct getproduct() {
TProduct[] Tproduct=null;
String[] hiber = request.getParameterValues("hiber");
String Hql = "from TProduct";
Map map = new HashMap();
List list = this.getList(Hql, map);
for (int i = 0; i < hiber.length; i++) {
if (hiber[i].equals(true)) {
Tproduct[i]=(TProduct)list.get(i-1);
}
return Tproduct[i];
}
return null;
}
问题说的有点错,我的意思是在外面声明全局变量如何在for循环里使用,大家请看这段代码里的return Tproduct[i];
这样的话for循环只会走了一遍,小弟想在外面声明这个变量然后把return Tproduct[i];
放在return null;
的位置上。

定义一个外部变量》将for里面的变量赋值给外部变量即可。因为for中的变量是不能被外部使用的。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-26
public TProduct getproduct() {
TProduct[] Tproduct=null;
String[] hiber = request.getParameterValues("hiber");
String Hql = "from TProduct";
Map map = new HashMap();
List list = this.getList(Hql, map);
TProduct tmp = null;
for (int i = 0; i < hiber.length; i++) {
if (hiber[i].equals(true)) {
tmp=(TProduct)list.get(i-1);
break;
}
//return Tproduct[i];
}
return tmp;
}

这样可以达你的要求吗?
另外。(TProduct)list.get(i-1);
这个是有问题的,当i=0时,如果你进行这个操作。
list.get(-1);
就会出错了。
会出下边的异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1本回答被网友采纳
相似回答