+ 3

How to go about creating multiple objects based on player input?

I am trying to figure out how to effectively design a method which will create an Array of objects (minimum of 2, maximum of 4) based on user input. (I.e. if user enters 3, array will contain 3 objects.) static void setArray(int x){ switch (x){ case 4: ArrayTest a = new ArrayTest(); ArrayTest b = new ArrayTest(); ArrayTest c = new ArrayTest(); ArrayTest d = new ArrayTest(); test[] = {a, b, c, d}; break; case 3: etc.... This is a partial code from method I'm using. Am I approaching this the right way?

19th Jun 2017, 4:11 PM
Mark Paramonte
Mark Paramonte - avatar
5 Réponses
+ 6
ArrayTest[] test = new ArrayTest[x]; for(int i = 0; i < test.length; i++) test[i] = new ArrayTest(); That's equivalent to all those switch cases object creations, but also more practical as it works for any x, x >= 0. It's also far less code and easier to read IMO. The array is also garbage collected after the method is finished running. Consider returning the array, or setting the value of some other array to the new one.
19th Jun 2017, 5:14 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
@Rrestoring Thank you for offering this solution! I knew there had to be a more practical way of making this work and you nailed it. much appreciated!!!
19th Jun 2017, 5:32 PM
Mark Paramonte
Mark Paramonte - avatar
+ 1
https://code.sololearn.com/c59V05cgHm6C/?ref=app link to the full code I have currently, if anyone is interested in looking further.
19th Jun 2017, 4:14 PM
Mark Paramonte
Mark Paramonte - avatar
+ 1
@Jamie The Scanner object is declared in main and named "input"
19th Jun 2017, 4:30 PM
Mark Paramonte
Mark Paramonte - avatar
0
I can't see the user input object. Where is the Scanner/Buffered Reader?
19th Jun 2017, 4:15 PM
Jamie Isaksen
Jamie Isaksen - avatar