Saturday, February 13, 2016

Get 4 "different" numbers

It is easy to just get 4 numbers. But it is difficult to get 4 numbers which are different from each other. This is the code to get 4 different numbers.

public static void main(String[] args){
    int[] answer = new int[4];
    for(int i = 0; i < answer.length; i++){
        Loop: while(true){
            answer[i] = (int)(Math.random() * 10);  //Random numbers between 0 and 9
            for(int j = 0; j < i; j++){
                //If one is same as one of the previous numbers, the loop is repeated
                if(answer[j] == answer[i]) continue Loop;
            }
            break;
        }
    }
}