Saturday, 15 August 2015

java - random numbers 1-10 without repeating. Why does this code not work. It compiles but still repeats -



java - random numbers 1-10 without repeating. Why does this code not work. It compiles but still repeats -

this code repeats numbers , if statement wrote in don't think should

class randomnumber { public static void main(string[] args) { int y = 0; int z = 0; int[] q = new int[10]; while(y != q.length) { int x = (int) (math.random() * 10); if (x != q[0] || x != q[1] || x != q[2] || x != q[3] || x != q[4] || x != q[5] || x != q[6] || x != q[7] || x != q[8] || x != q[9]) { q[z] = x; system.out.println(q[z]); // or print x doesn't matter y++; // chose 1 create sure each z++; // q[] getting set value } } } }

you should utilize , and not or in condition, since x must different elements in array.

that said, should note array initialized 0s, if 0 1 of valid values wish have in random array, loop never terminate.

i check duplicates in sub-array initialized :

int z = 0; while(z != q.length) { int x = (int) (math.random() * 10); boolean isdup=false; (int i=0;i<z&&!isdup;i++) { if (x==q[i]) isdup=true; } if (!isdup) { q[z] = x; system.out.println(q[z]); z++; } }

btw, y , z same, don't need them both.

java

No comments:

Post a Comment