Removing a randomly picked element from a Java Array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Removing a randomly picked element from a Java Array?

I created a code that would randomly pick a card from a 52 card deck. The game is over when the Ace of Spades is picked. I used an array with 52 different elements for each card. I want to make it so that when it doesn't pick the Ace of Spades, it removes the incorrect card from the deck so you can't go over 52 guesses. Does anyone know how I could remove an element from the array when the element is picked randomly? When I researched removing elements from an array, all of them use the index value they want to remove, but I don't know how to do that when it's picked at random. https://code.sololearn.com/c5lUcYd30pMG

14th Jan 2018, 3:39 AM
Jacob Garcia
Jacob Garcia - avatar
5 Answers
+ 1
Definitely not the most elegant solution. But, it does the job. Replace card with "", if we get a empty card loop to the next available. https://code.sololearn.com/cH9pYnNhDm3l/?ref=app
14th Jan 2018, 4:07 AM
John Wells
John Wells - avatar
+ 1
Oh wow, I should have thought of creating another variable for actually picking the card. Thank you so much :)
14th Jan 2018, 4:17 AM
Jacob Garcia
Jacob Garcia - avatar
0
Ok, I think I see what you mean, but I'm still confused as to how I would implement it. I'd have to decrease the array by 1 after the print statement? Something like... cards = cards.length - 1 ?
14th Jan 2018, 4:08 AM
Jacob Garcia
Jacob Garcia - avatar
0
Ace's response is move the cards towards 0 to overwrite the one selected moving everything after it down one and decrement the length.
14th Jan 2018, 4:13 AM
John Wells
John Wells - avatar
0
an array isnt the best datastructure for this, use an arraylist instead
14th Jan 2018, 7:00 AM
Jeremy
Jeremy - avatar