Why do I get a stack overflow error on this code?

时间:2015-05-24 22:08:59

标签: java arrays stack overflow

Basically, I'm trying to generate an array of 9 integers which contains the numbers 1-9 in a way that they are not duplicated.

public static int[] generate (){

    //new int array
    int[] arr = new int[9];

    //filling the array with random numbers
    for(int i=0;i<arr.length;i++){
        arr[i]=rand.nextInt(9)+1;
    }

    //boolean which turns true if a number is twice in the array
    boolean same=false;

    //checking if there are double numbers
    for(int i=0;i<arr.length;i++){
        for(int j=0;j<arr.length;j++){
            if(arr[i]==arr[j]){
                same=true;
            }
        }
    }

    //returning the array if all numbers are different
    if(same==false){
        return arr;
    }

    //repeating if there is a double number
    else{
        return generate();
    }
}

I know that the code might be very inefficient but I am quite new to Java and I want to solve it in a way like that. I'm very thankful for every help!

0 个答案:

没有答案