Using Java - Can I use a switch statement inside of an Object[] declaration to populate the object array based on player input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Using Java - Can I use a switch statement inside of an Object[] declaration to populate the object array based on player input?

I'm trying to figure out a way to implement the option to add up to 4 other AI players to a game (for a Max of 6, min of 2). I want an array of objects, (my Player() object). players[0] = new Player(sc.next()); for the user named object. players[1] = new Player() for my default object those would be the minimum requirements to play. If user wants 6 players, I want to fill array with 4 more Player objects with different names that I'll pull from a String[]. https://code.sololearn.com/cg56njI26Mp3/?ref=app

2nd Jun 2017, 4:02 AM
Mark Paramonte
Mark Paramonte - avatar
4 Answers
+ 2
What if you made all the computer/player objects, but use the switch statement to determine how many will be utilized based on player input?
2nd Jun 2017, 4:28 AM
Joseph P French
Joseph P French - avatar
+ 11
Another way to go about it might be to use a dynamic container (perhaps ArrayList?, I'm not sure if that's the one I'm thinking of). Then you can build the group of players (both carbon and silicon based) to order one you know how many of each is requested. It's certainly more overhead that way, but it gives you some flexibility. Just make sure to check the limits of that object before you go walking through it, our you'll get runtime errors.
2nd Jun 2017, 4:48 AM
Jim
Jim - avatar
+ 6
I think I'll give that a try. Thank you
2nd Jun 2017, 4:29 AM
Mark Paramonte
Mark Paramonte - avatar
+ 5
I'm going to attempt using ArrayList, especially because I haven't worked with them before. I also realized I'll have better luck setting this up in a static Object[] return method in my player class, and also set up methods that allow me to traverse the Elements within the ArrayList. Thanks for your input! Much appreciated
2nd Jun 2017, 5:59 AM
Mark Paramonte
Mark Paramonte - avatar