using loop, I can create
My cat is: Cat1
...
My cat is: Cat1
However, when I tried to use
Cat ("cat"+i) = new Cat("Cat" + i);
I’m making mistakes….
So, what is the simplist way to correct my code to produce
cat1 ... cat10 cat instances?
public class TestCat{
public static void main(String [] args){
for (int i=1; i<10; i++){
//Cat ("cat"+i) = new Cat("Cat 1");
Cat cat1 = new Cat("Cat 1");
System.out.println("My cat is: " + cat1 );
}
}
}
class Cat{
static String catName;
public Cat(String catName){
this.catName=catName;
}
public String toString(){
return catName;
}
}
Sorry….I should say
How to create ten 10 Cat instances…..cat1, …cat2…..because in other languages, I can use “cat”||i = …, to create different varaibles, I wonder how I could do similar things in Java….
In other words, I want to name the instances I’m going to create by taking the loop information into account.
Use a collection if you don’t know how many cats you’ll have.
Note: This code produces incorrect results and had me stumped until I looked closer at the Cat class.
Here was the culprit:
Remove the
staticand you are golden.