dtrembl5 dtrembl5 - 1 month ago 10
Java Question

Incorrect output for an array, java

The code below simulates dice, I am interested in the number of times the two dice will match and the idea is to print out 0 and 1 at first to show how often this happens. Then to print the array which should contain when was obtained the "double", ex: the first would contain 3, which is the number of throw before the first double...a limit of lets say 45 given by the user will end the program.

public static void main(String[] args) {
int limiteDoublons = Integer.parseInt(JOptionPane.showInputDialog("Nombre lancer: ").trim());
int[] t = new int[limiteDoublons];
int d1 = 0;
int d2 = 0;
int nbDoublons = 0;
int nbLancer = 0;
do {
for(int x = 0; x<limiteDoublons;x++){
//shuffle
d1 = (int)(Math.random() * 7) + 1;
d2 = (int)(Math.random() * 7) + 1;
//si doublon print 1 et augmente le nbDoublon
//donne la valeur du tableau suivante ;a valeur de nblancer
if(d1 == d2) {
System.out.print("1");
nbDoublons++;
t[x] = nbLancer;
}
else {
System.out.print("0");
}
if ((nbLancer + 1) % 20 == 0) {
System.out.println();
}
nbLancer++;
}
} while (nbDoublons < limiteDoublons);

System.out.println("\nOrdre des boulons: ");
Arrays.sort(t);
for (int i = 0; i < limiteDoublons; i++) {
System.out.printf("%1$4d", t[i]);
if ((i + 1) % 10 == 0)
System.out.println();
}
}


}

Now everytime I compile, I get a certain amout of zeros and then the real numbers of throw for my doubles. Why all the zeros?

Output:

10001101100000000000
01001100000000000000
00000000000000000000
00101100010100110010
00000000000000100000
00001100010010000000
00000000100000000000
00001000000000000000
01000100000011000101
00000010001000000100
00000001000000000100
01010000000000100001
01100100100000001000
10000000001010010000
00001000000000000000
000000000100000
Ordre des boulons:
0 0 0 0 0 0 0 0 0 0
0 7 8 21 25 69 74 78 94 105
109 112 161 165 173 177 179 186 190 207
217 221 223 234 241 242 245 248 256 260
270 272 275 284 309


What is unexpected is the 0 following "Ordre des boulons". It doesnt make sense that I would get my first double at the throw 0 and so on...

Answer

You're getting all the zeros because you're updating the array at index x, which is counting throws, not doubles. You should use nbDoublons instead:

t[nbDoublons] = nbLancer;
nbDoublons++;
Comments