Set of 3 Java ports

Asked

Viewed 263 times

0

I have to do an exercise in Java that consists in creating a matrix [3][3] and each line would be a phase of the game. The user should guess which door the prize is in. For this I need to make a Random in each row assigning the value 1 to the premium port and 0 to the others, the question is how do I do this Random line by line?

1 answer

4


The class java.util.Random has a method nextInt(int) that returns an integer in the range [0,n[, given a n input. Using 3, it will return a number on [0,1,2]. Then just assign the port with that number to 1, and keep the others with 0:

Random r = new Random();
// para cada linha
int qual = r.nextInt(3);
linha[qual] = 1;
  • Thank you for the reply mgibsonbr, I will try here.

  • @Marciorezende I saw the code you posted and deleted, you must have solved it yourself, but if not, two tips: 1) Put the giveaway inside the loop, not outside (otherwise the door drawn will be the same every time); 2) You don’t need an internal loop, because integer arrays in Java are already initialized with everything zero - just do porta[i][qual] = 1.

  • mgibsonbr, it was worth the strength. I saw that I was doing nonsense, I have a teacher who does not teach, exercise or correct. I am learning more here with you than in class :). Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.