开发者

Creating New Object of Other Class dynamicly?

开发者 https://www.devze.com 2022-12-23 08:01 出处:网络
I am tryıng to create new object of other class ın a for loop. like for(int i =0;i<10;i++){ Computerp1=new Computer(10,20);

I am tryıng to create new object of other class ın a for loop. like

for(int i =0;i<10;i++){
 Computer  p1=new Computer(10,20);
}

and when I try anywhere开发者_JAVA百科 to reach p1.someAction(); it say you must declare p1. But if I declare it on top of program how can I create again in loop? I also try only Computer p1; but it gave exeption ..


p1 only exists within the scope of the containing block. i.e. 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.

e.g.

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...
0

精彩评论

暂无评论...
验证码 换一张
取 消