lundi 24 juillet 2017

while loop leads to a bug

This is my code

import java.util.Scanner; //make use of scanner class to input values
import java.util.Random; //get random number


public class MarkSix5
{
    public static void main(String[] args)
    {
    final int SIZE_OF_MARKSIX = 7;
    final int SIZE_OF_PERIODS = 5;

//Ask user to enter how many periods of draw results he/she wants
Scanner input = new Scanner(System.in);

int[] markSix = new int[SIZE_OF_MARKSIX * SIZE_OF_PERIODS];

//Ask user to enter the past results
for(int j=0; j<5; j++)
{   
    int temp=0;
    String periodNumber="";
    if (j==0) periodNumber="1st";
    else if (j==1){periodNumber="2nd";temp =7;}
    else if (j==2){periodNumber="3rd";temp=14;}
    else if (j==3){periodNumber="4th";temp=21;}
    else {periodNumber="5th";temp=28;}

    System.out.print("Please enter the past results of the " + periodNumber + " MarkSix: ");

    for(int i=1*temp; i<SIZE_OF_MARKSIX+temp; i++)
        {
            markSix[i]=input.nextInt();
        }

    System.out.println("");
}

//generate random numbers
Random rand = new Random();
int[] theRandomNumber = new int[6];
int decision=1;    
do
{
//initialize the new set of numbers
for(int k =0; k<6; k++)
    {
        theRandomNumber[k] = rand.nextInt(49)+1;
    }
//check that the new set of numbers with conditions
for(int a=0;a<7;a++){ //need to consider how many times to check
for(int k=0;k<6;k++)
    {
        for(int j=0; j<35;j++) //ensure no past draw numbers
            {
                while (theRandomNumber[k]==markSix[j])//**This is the bug**
                {                       
                    theRandomNumber[k] = rand.nextInt(49)+1;
                }
            }

           { for(int j=0; j<6;j++) //check duplicate numbers
            {          
                while (theRandomNumber[k]==theRandomNumber[j])//**This is the bug**
                {
                    theRandomNumber[k] = rand.nextInt(49)+1;                
                }
            }
        }
    }
}

//print out results
System.out.println("A new set of numbers: " +theRandomNumber[0] + " " +theRandomNumber[1] + " "+theRandomNumber[2]+" "+ theRandomNumber[3]+ " " +theRandomNumber[4]+ " "+theRandomNumber[5]+".");
System.out.println("Do you want to have another set of numbers?(if yes, type 0)");  
decision = input.nextInt();

}while (decision==0);  
    }

}

The program should first ask user to enter 5 sets of numbers. And then print out a new set of numbers that does not exist in the 5 sets of numbers.

When I use while loop, my program stops here. enter image description here

After I change while to if, it works. But I cannot figure out why while loop does not work.

Aucun commentaire:

Enregistrer un commentaire