-2

I'm creating a small program that extracts 3 random numbers, the only condition is that all three numbers must be different from each other, for example: 3,9,3 is not acceptable.

This i my code, i tried it several times and occasionally appear numbers equal to each other.

What is wrong in my code ?

public class Premi {
public static void main(String[] args) {
    int num = (int) (Math.random() *10) + 1;
    int num2 = (int) (Math.random() *10) + 1;
    int num3 = (int) (Math.random() *10) + 1;
    boolean first = true;
    boolean second = true;
    boolean third = true;
    while(first) {
        if (num!=num2) {
            first=false;
        } else if (num==num2) {
            num = (int) (Math.random() *10) + 1;
        }   
    }
    while(second) {
        if (num!=num3) {
            second=false;
        } else if (num==num3) {
            num = (int) (Math.random() *10) + 1;
        }   
    }
    while(third) {
        if (num2!=num3) {
            third=false;
        } else if (num2==num3) {
            num2 = (int) (Math.random() *10) + 1;
        }   
    }
    System.out.println(num + "," + num2 + "," + num3);
}
}

Thank you.

Fetex
  • 90
  • 6

1 Answers1

1
Set<Integer> numbers = new HashSet<>();
while (numbers.size() < 3)
    numbers.add(((int) (Math.random() *10) + 1));

Using Set here will guarantee that the numbers are not repeating.

And if you're not allowed to use any collections or arrays (I'll reserve my opinion of courses that forbid students to use valid techniques) you can use:

int n1 = (int) (Math.random() * 10) + 1;
int n2;
do {
    n2 = (int) (Math.random() * 10) + 1;
} while (n2 == n1);
int n3;
do {
    n3 = (int) (Math.random() * 10) + 1;
} while (n3 == n2 || n3 == n1);

The do loop is guaranteed to run at least once.

Alex Savitsky
  • 2,306
  • 5
  • 24
  • 30