+ 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
6 Antworten
+ 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
+ 1
Oh wow, I should have thought of creating another variable for actually picking the card. Thank you so much :)
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
?
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.
0
an array isnt the best datastructure for this, use an arraylist instead