0

I'm trying to create some classes but the number of them is determined by the user. The class I want to make:

public class test {
   public class test() {
      int num;
      //etc.
   }
}

Main class:

public class main {
   public static void main(String[] args) {
      test class1 = new test();
      test class2 = new test();
      test class3 = new test();
      //etc.
   }
}

The problem is that currently the maximum amount of classes the user can create depends on my patience.

Is there a way to make it easier/shorter?

Ps: The project I want to use this for doesn't work with lists!

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
Error503
  • 11
  • 1
  • 3
  • 1
    Can you use Arrays? Because this can be solved easily with an Array – Gatusko Oct 25 '18 at 18:15
  • 1
    You have 2 problems to solve - one is to have lots of a thing without creating a variable for each one - for this you need a variable you can store more than one thing in: an array or a list. The second problem is to do the same thing repeatedly - i.e. you need a loop (a for() loop would be the normal way to do this in java) – Will Oct 25 '18 at 18:16

3 Answers3

0

You can use a for loop and save your objects in a list:

public static void main(String[] args) {
      int n = 10; //a number given 
      List<Test> myObjs = new ArrayList<Test>();
      for(int i = 0, i < n, i ++) {
        Test t = new Test();
        myObjs.add(t);
      }
}
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
0

You can utilize an array (Test[]) or a list (List<Test>) or any other data structure you like to hold your Test objects.

public class Test {
    private int num;

    public Test(int num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return String.format("Test %d", this.num); // Override the toString() method
    }
}
public class Main {
    public static void main(String[] args) {
        List<Test> tests = new ArrayList<>();
        int n = 5; // Create five tests

        for (int i = 0; i < n; n++) {
            tests.add(new Test(i)); // Instantiate and add tests to list
        }

        for (Test test : tests) {
            System.out.println(test.toString()); // Print the contents i.e. `num`
        }
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

just use an array

public class MyClass
{ 
    public static void main(String[] args){    
        MyClass myClass[]=null;
        for(int i = 0; i < 5; i++){
           myClass[i] =new MyClass(); 
        }               
    }
}
DCR
  • 14,737
  • 12
  • 52
  • 115