Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m really curious - I\'m a beginner for Java and I was wondering if someone ca

ID: 3570152 • Letter: I

Question

I'm really curious - I'm a beginner for Java and I was wondering if someone can explain what this means? It's from a card game and I know that it's supposed to create random values, but what do i, j, temp, cards[i], and cards[j] stand for? Thorough answers would be appreciated, because I'm super confused. Thanks in advance!

Random generator = new Random();
for (int i=0; i<=100; i++);
int i=generator.nextInt(cards.length);
int j=generator.nextInt(cards.length);
temp=cards[i];
cards[i]=cards[j];
cards[j]=temp;

Explanation / Answer

cards[]
cards is an array of cards, each having some number to identify them.
Like for example, if there are 10 different cards, having the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
these numbers are stored in the array cards[].
card[i] refers to the card number at the ith index, and card[j] refers to the card at jth index(index starts from 0). Example, if we say cards[0], we refer to the card numbered 1, card[2] means the card at 3rd location, ie card number 3, and so on.


i, j
These are variables used to select 2 different card numbers.
Like, if there are cards from the previous example, we select 2 card numbers at random(in the statements(int i=generator.nextInt(cards.length); and int j=generator.nextInt(cards.length);).


temp
it is a temporary variable used to swap 2 cards.
After you have selected 2 cards from the previous step, we can swap the 2 cards as follows:

store the number of first selected card in a temporary variable, named temp.
Then store the number of second selected card in the index of first selected card.
Then, store the number of the first selected card(which was stored temporarily in temp) in the second index.