[英]Creating New Object of Other Class dynamicly?
I am tryıng to create new object of other class ın a for loop. 我正在尝试创建for循环的其他类的新对象。 like
喜欢
for(int i =0;i<10;i++){
Computer p1=new Computer(10,20);
}
and when I try anywhere to reach p1.someAction(); 当我尝试在任何地方到达p1.someAction(); it say you must declare p1.
它说您必须声明p1。 But if I declare it on top of program how can I create again in loop?
但是,如果我在程序顶部声明它,如何在循环中再次创建? I also try only Computer p1;
我也只尝试计算机p1; but it gave exeption ..
但它给了exeption ..
p1
only exists within the scope of the containing block. p1
仅存在于包含块的范围内。 ie within {...}
. 即在
{...}
。
So you either need to use p1 within this block, or (and I suspect this is what you want) store each Computer
object in a collection (say, an ArrayList
) and use them outside the loop. 因此,您要么需要在此块中使用p1,要么(我怀疑这就是您想要的)将每个
Computer
对象存储在一个集合中(例如ArrayList
),然后在循环外使用它们。
eg 例如
List<Computer> ps = new ArrayList<Computer>();
for(int i =0;i<10;i++){
ps.add(new Computer(10,20));
}
// now use the list contents here...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.