Get out of loop to finish program?
This program is supposed to make 10 unique #s in an array, it outputs correctly, but it is stuck in the while loop. hHow can I get out?
Quote:
import java.util.Random;
public class Extra {
public static void main(String[] args) {
// Variables
int rand;
int [] unique = new int [11];
boolean [] check = new boolean [11];
Random generator = new Random();
// Welcome
System.out.print("Here are your ten unique array values: ");
// Set Arrays
for(int counti = 0; counti < unique.length; counti++) {
check[counti] = false;
}
// Set Array
for(int count = 0; count < unique.length; count++) {
if(check[unique[count]] == false){
check[unique[count]] = true;
System.out.print(unique[count] + " ");
}
else{
while(check[unique[count]] == true) {
unique[count] = generator.nextInt(10) + 1;
if(check[unique[count]] == false){
check[unique[count]] = true;
System.out.print(unique[count] + " ");
}
if(count > 2){
break;
}
}
}
}
}
/**
Here are your ten unique array values: 437521689
*/
Re: Get out of loop to finish program?
Code java:
while (check[unique[count]] == true) {
System.out.println("check[unique[count]] " +check[unique[count]] );
System.out.println("in while " + number);
unique[count] = generator.nextInt(10) + 1;
if (check[unique[count]] == false) {
check[unique[count]] = true;
System.out.print(unique[count] + " ");
}
if (count > 2) {
break;
}
number++;
}
when do you set your check to false?
add some print out lines like above...
Re: Get out of loop to finish program?
this is what the output turns to be:
Here are your ten unique array values: 103127check[unique[count]] true
in while 0
9 check[unique[count]] true
in while 0
check[unique[count]] true
in while 0
8 check[unique[count]] true
in while 0
check[unique[count]] true
in while 0
4
Process completed.
and my check is set in the for loop :
for(int counti = 0; counti < unique.length; counti++) {
check[counti] = false;
}
Re: Get out of loop to finish program?
Quote:
check[unique[count]] true
in while 0
it is here that your problem is. you never set your check to false in your while loop to drop out.
you can use a different while loop or not use it at all.
put your display loop after your for loop set Array and you may see different results.
after reworking your code (re-arranged)
here is my results
Here are your ten unique array values: 0 0 4 2 7 1 1 6 3 4 6 6
BUILD SUCCESSFUL (total time: 0 seconds)