mercredi 29 juin 2016

Java: Format elements and count number of reoccurring elements in a 2d array

I'm trying to determine how many times each number between 0-999 has been used in the array. Also I'm wanting to format the elements so that its always a 3 digit number. instead of '21' it would be '021', '5' would be '005'. Netbeans is saying to use an enhanced loop in place of for(int x=0;x

public static void main(String[] args) {
    //Creator of random number 0-999
    Random creator = new Random(999);

    int lotto[][] = new int[1000][2];
    int count = 0;

    for(int x=0;x<lotto.length; x++){
        for(int y = 0; y < lotto[x].length; y++){
            //Fills element with random number
            lotto[x][y] = creator.nextInt(999);
        }
    }
    //Place holder to print out array
    for(int[] a: lotto){
        System.out.println(Arrays.toString(a));
    }
}

}

Edit: I've tried this

for(int x=0;x<lotto.length; x++){
        for(int y = 0; y < lotto[x].length; y++){
            //Fills element with random number
            ++lotto[creator.nextInt(999)][creator.nextInt(999)];
        }
    }
 for(int j=0; j < lotto.length;j++){
        System.out.println(j +""+ lotto[j]);
 }

But now the program doesnt run. I think the ++lotto is right to count how many time that element is used.

Edit 2:

 List<Integer> list = new ArrayList<>();
    for(int x=0;x<lotto.length;x++){
        for(int y=0; y<lotto[x].length; y++){
            list.add(lotto[x][y]);
        }
    }
    for(int x=0; x<1000; x++){
        if(list.contains(x)){
            int index = 0;
            int countList = 0;
            while(index!= -1){
                countList++;
                list.remove(index);
                index = list.indexOf(x);
            }
            System.out.println(x +" Hit "+ countList + "time(s)");
        }
    }

When the array prints out, theres 1 less the number of found elements in the array as what the list is printing out.

UPDATE: For some reason now the source below to count the list, the number doesnt match the count of the number of times the user's input is. ie: user inputs 200, it counts 200 was used twice but the list only prints out it was found once

for(int x=0;x<lotto.length;x++){
        for(int y = 0; y < lotto[x].length; y++){
            if(lotto[x][y]== lottery)
                count++;
        }
    }

Aucun commentaire:

Enregistrer un commentaire