简体   繁体   中英

How to create an instance of a class with a variable string name in Java?

sorry if this has been posted under a different title which I'm sure it has but I failed at finding it.

Say you have the following code:

public class Main{
    public static void main(String[] args)
    {
        String[] names = {"James", "Allison"};
        int[] ages = {10, 12};

        for (int i = 0; i < names.length; i++)
        {
            Item names[i] = new Item(ages[i]);//line that will produce the error
    }
}

class Item{
    private int age;

    Item(int theirAge){
        age = theirAge;
    }
}

Now this code will produce a duplicate variable error which comes from the names[i] variable already being defined as a String but now we are trying to define it as an Item. I have tried quite a few things but just can't seem to get it.

public class Main {
      public static void main(String[] args){
             String[] names = {"James", "Allison"};// variable a
             int[] ages = {10, 12};

             for (int i = 0; i < names.length; i++){
                Item names[i] = new Item(ages[i]);//variable b
             }
}

class Item{
     private int age;
     Item(int theirAge){
     age = theirAge;
     }
}

Because you have two variables have the same name, variable a and variable b. The solution for you would be either you change the variable b's name, or use the existing variable without declaration it again. However, in this case, you have different type from A to B. You cannot use the existing variable. You just have to declare a new Item object, but different name.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM