简体   繁体   中英

Calling arbitrary number of object instances

import java.util.*;
public class UserInput {
    public static void main(String[]args){
        Scanner input = new Scanner(System.in);
        System.out.println("How many students are in your class?");
        Student.n= input.nextInt();
        for(int i=0; i<Student.n; i++){
            Student i = new Student(null, null, null, null, 0);
        }

    }
}

I am new to java and was just wondering if it's possible to call a number of object instances from a value inputted by the user during run time. Here "n" is the number of instances I want to make and I thought I could use the for method to refer to a variable "i" where it would create a new object instance for every "i" until it reached the inputted value of "n". However, I get a duplicate local variable error. So just wondering if there is any way around this????

One possible way is this:

ArrayList<Student> manyStudents = new ArrayList<Student>();
for(int i=0; i<Student.n; i++){
    manyStudents.add(new Student(null, null, null, null, 0));
}

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