10 Replies - 931 Views - Last Post: 09 May 2012 - 12:24 PM Rate Topic: -----

#1 MrsQ  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 20-September 08

Method to check for duplicate number does not work

Posted 07 May 2012 - 04:08 PM

I'm working on an assignment for a Lottery Quick Pick program that requires me to create the method private boolean numberUsed(int intInNumber) and have it check if a number has already been picked. If it has, then I must look until I find an unused number. I tried calling it in a for statement to check and it was still returning duplicates. I switched to a while statement as below, and am still getting duplicates. I'm sure it's something simple that I'm not seeing, but I'm hoping someone here can see what I can't. Is the problem with the method numberUsed() or is it how I am calling it in the method getQuickPicks() ?

*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

//Begin lotteryQuickPick class
public class lotteryQuickPick
{
	//Declare the variables to be returned from the methods:
	private boolean boolFound = false;

	private int intTotalNumbersToPlay = 0;
	private int intNumberOfPicks = 0;


	private int intArrayQP[] = new int[0];

		//Code the constructor to accept the user's numbers to the class:
	public lotteryQuickPick()
	{

	}

	public lotteryQuickPick(int intTotNum, int intNumPicks)
	{
		intTotalNumbersToPlay = intTotNum;
		intNumberOfPicks = intNumPicks;
	}

/****************************************************************************************************/
//METHODS to return the different results from the different methods and write out to the JTextArea://
/****************************************************************************************************/

//Method to clear the array for each new Quick Pick generation
private void initializeArray()
{
	intArrayQP = new int[0];

} //end initializeArray method

//Method to return a randomly generated number within the range
private int getNumber()
{
	int intRandomNum = 0;
	intRandomNum = 1 + (int)(Math.random()* intTotalNumbersToPlay);

	return intRandomNum;
} //end getNumber method

//Method to check if a number has already been picked.
private boolean numberUsed(int intInNumber)
{
	int intIndex = 0;
	int intNumToCheck = intInNumber;
	boolean boolNumFound = false;

	while (intIndex < intArrayQP.length && !boolNumFound)
	{	if (intArrayQP[intIndex] == intNumToCheck)
			boolNumFound = true;
		else
			intIndex++;
	}
	return boolNumFound;

}//end numberUsed method

//method to return the requested Quick Pick number set to the screen
public int[] getQuickPicks()
{
	int[] intArrayQP = new int[intNumberOfPicks];

	int intIndex = 0;

	while (intIndex < intArrayQP.length)
	{
		intArrayQP[intIndex] = getNumber(); //populate the array

		boolFound = numberUsed(intArrayQP[intIndex]); //check that the number is not a duplicate

		while (boolFound == true) //if the number IS a duplicate, repeat the process until it isn't
		{
			intArrayQP[intIndex] = getNumber();

			boolFound = numberUsed(intArrayQP[intIndex]);
		}

		intIndex++;
	}

	    //Next we sort the numbers:
		java.util.Arrays.sort(intArrayQP);

		//return the numbers in the array
		return intArrayQP;

}//end getQuickPicks method

}//End lotteryQuickPick class



Is This A Good Question/Topic? 0
  • +

Replies To: Method to check for duplicate number does not work

#2 37Liion  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 2
  • View blog
  • Posts: 49
  • Joined: 18-February 10

Re: Method to check for duplicate number does not work

Posted 07 May 2012 - 04:49 PM

I would say duplicate and sort (or sort, check, shuffle) the array then check if array[i] == array[i-1] for each index.

Outside of that you've got hash maps which are fun to learn..

ArrayLists..
Random random = new Random();
ArrayList<int> list = new ArrayList<int>();
int randomInt;
for(int i=0;i<NUMBER_OF_RANDOMS;i++)
{
    do {
    randomInt = random.nextInt(MAX);
    } while(list.contains(randomInt));
    
    list.add(randomInt)
}



Associative arrays exist in some form.. similar to hash maps

This post has been edited by 37Liion: 07 May 2012 - 04:50 PM

Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Method to check for duplicate number does not work

Posted 07 May 2012 - 04:51 PM

Why don't you simply

boolean numberInUsed(int number) {
   for(int i = 0; i < array.length(); ++i) {
       if(array[i] == number)
         return true;
   }
   return false;
}


Was This Post Helpful? 1
  • +
  • -

#4 MrsQ  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 20-September 08

Re: Method to check for duplicate number does not work

Posted 07 May 2012 - 07:59 PM

I changed the numberUsed() method per your suggestion, and it certainly makes sense that that should work, however it still doesn't. I'm certain it's got something to do with my call to the method, but I can't for the life of me see it - could just be that I've been looking too hard and too long, so maybe someone else can see what I can't?

I'll post the class that calls this class as well, maybe that will make it clearer what I'm trying to accomplish versus what I'm getting.

//Begin lotteryQuickPick class
public class lotteryQuickPick
{
	//Declare the variables to be returned from the methods:
	protected boolean boolFound = false; //change to private after testing**************

	private int intTotalNumbersToPlay = 0;
	private int intNumberOfPicks = 0;


	private int[] intArrayQP = new int[0];

		//Code the constructor to accept the user's numbers to the class:
	public lotteryQuickPick()
	{

	}

	public lotteryQuickPick(int intTotNum, int intNumPicks)
	{
		intTotalNumbersToPlay = intTotNum;
		intNumberOfPicks = intNumPicks;
	}

/****************************************************************************************************/
//METHODS to return the different results from the different methods and write out to the JTextArea://
/****************************************************************************************************/

//Method to clear the array for each new Quick Pick generation
private void initializeArray()
{
	intArrayQP = new int[0];

} //end initializeArray method

//Method to return a randomly generated number within the range
private int getNumber()
{
	int intRandomNum = 0;
	intRandomNum = 1 + (int)(Math.random()* intTotalNumbersToPlay);

	return intRandomNum;
} //end getNumber method

//Method to check if a number has already been picked.
private boolean numberUsed(int intInNumber)
{
	int intNumToCheck = intInNumber;

	for(int intIndex = 1; intIndex < intArrayQP.length; intIndex++)
	{
		if(intArrayQP[intIndex - 1] == intNumToCheck)
			return true;
	}

	return false;

}//end numberUsed method

//method to return the requested Quick Pick number set to the screen
public int[] getQuickPicks()
{
	int[] intArrayQP = new int[intNumberOfPicks];

	int intIndex = 0;

	while (intIndex < intArrayQP.length)
	{

		intArrayQP[intIndex] = getNumber(); //populate the array

		//check that the number is not a duplicate
		while (numberUsed(intArrayQP[intIndex]) == true) //if the number IS a duplicate, repeat the process until it isn't
		{
			intArrayQP[intIndex] = getNumber();

			numberUsed(intArrayQP[intIndex]);
		}

		intIndex++;//once a unique number is found, get the next number

	}

	    //Next we sort the numbers:
		java.util.Arrays.sort(intArrayQP);

		//return the numbers in the array
		return intArrayQP;

}//end getQuickPicks method

}//End lotteryQuickPick class



public class lotteryQuickPickJFrame extends JFrame
{
    // Declare constants
    private static final int WIDTH=400;
    private static final int HEIGHT=400;

    // Declare JFrame components

    private JLabel     jlblTotalNumbers,
    				   jlblTotalPicks,
    				   jlblPlays;

    private JTextField jtxtTotalNumbers,
    				   jtxtTotalPicks,
    				   jtxtPlays;

    //  JTextArea:
    private JTextArea  jtaLotteryNumbers;

    // JButtons:
    private JButton    jbutLottery,
                       jbutClear,
                       jbutExit;

    // Event Handlers:
    private LotteryQuickPickButtonHandler lqpButtonHandler;
    private ClearButtonHandler            cbHandler;
    private ExitButtonHandler             ebHandler;

    // JScrollbar:
    private JScrollPane scrollingResult;

    // JPanels:
    JPanel jpnlMain   = new JPanel();
    JPanel jpnlCenter = new JPanel();
    JPanel jpnlNorth  = new JPanel();
    JPanel jpnlSouth  = new JPanel();

	// Constructor
    public lotteryQuickPickJFrame()
    {
		// Set the title and size:
        setTitle("Lottery Quick Pick");
        setSize(WIDTH, HEIGHT);

		// Set the layouts
        jpnlMain.setLayout(new BorderLayout(5, 5));

        jpnlNorth.setLayout(new GridLayout(3, 2, 5, 5));
		jpnlCenter.setLayout(new GridLayout(1, 1, 5, 5));
		jpnlSouth.setLayout(new GridLayout(1, 3, 5, 5));

		// Instantiate the components
        jtaLotteryNumbers = new JTextArea(20,1);
        jtaLotteryNumbers.setEditable(false); // User cannot enter values in this field
        scrollingResult = new JScrollPane(jtaLotteryNumbers); // Make the JTextArea scrollable

		// Instantiate and register the buttons for click events
        jbutLottery = new JButton("Quick Pick");
		lqpButtonHandler = new LotteryQuickPickButtonHandler();
		jbutLottery.addActionListener(lqpButtonHandler);

		jbutClear = new JButton("Clear");
		cbHandler = new ClearButtonHandler();
		jbutClear.addActionListener(cbHandler);

		jbutExit = new JButton("Exit");
		ebHandler = new ExitButtonHandler();
		jbutExit.addActionListener(ebHandler);

		// Add components to the North panel
		jlblTotalNumbers = new JLabel("Enter highest number:");
		jtxtTotalNumbers = new JTextField();
		jpnlNorth.add(jlblTotalNumbers);
        jpnlNorth.add(jtxtTotalNumbers);

        jlblTotalPicks = new JLabel("Enter the number of picks:");
		jtxtTotalPicks = new JTextField();
		jpnlNorth.add(jlblTotalPicks);
        jpnlNorth.add(jtxtTotalPicks);

        jlblPlays = new JLabel("Enter the number of plays:");
		jtxtPlays = new JTextField();
		jpnlNorth.add(jlblPlays);
        jpnlNorth.add(jtxtPlays);

		// Add components to the Center panel
        jpnlCenter.add(scrollingResult);

		// Add components to the South panel
		jpnlSouth.add(jbutLottery);
        jpnlSouth.add(jbutClear);
        jpnlSouth.add(jbutExit);

		// Finalize the screen layout and publish to the display
		jpnlMain.add(jpnlNorth, BorderLayout.NORTH);
		jpnlMain.add(jpnlCenter, BorderLayout.CENTER);
		jpnlMain.add(jpnlSouth, BorderLayout.SOUTH);

		// Prepare the containter
		Container ca = getContentPane();
		ca.add(jpnlMain);
      	setContentPane(ca);

        // Show the JFrame and set code to respond to the user clicking on the X
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    } // end crapsCasinoJFrame constructor


	// Pick Lottery click event
	private class LotteryQuickPickButtonHandler implements ActionListener
    {
      	public void actionPerformed(ActionEvent e)
      	{

          int intPlays = 0,
              intTotalNumbers = 0,
              intTotalPicks   = 0;

          int[] iArrayQuickPicks;

          String sNumbers;

          // Try to convert how many numbers:
	      try
	      {
			  intTotalNumbers = Integer.parseInt(jtxtTotalNumbers.getText());
	      }
          catch (Exception aeRef)
	      {
	        writeMessage("Please a number for the highest number.");
	        jtxtTotalNumbers.requestFocus();
	        return;
          }

           // Try to convert number of picks:
		  try
		  {
		  	  intTotalPicks = Integer.parseInt(jtxtTotalPicks.getText());
		  }
		  catch (Exception aeRef)
		  {
		      writeMessage("Please a number for the number of picks.");
		      jtxtTotalPicks.requestFocus();
		      return;
          }

          // Try to convert number of plays:
		  try
		  {
		  	  intPlays = Integer.parseInt(jtxtPlays.getText());
		  }
		  catch (Exception aeRef)
		  {
		      writeMessage("Please a number for the number of plays.");
		      jtxtPlays.requestFocus();
		      return;
          }

          // Make sure the total numbers is >= to the total picks:
          if ( intTotalNumbers < intTotalPicks )
          {
		      writeMessage("The highest number must be >= total picks.");
		      jtxtTotalNumbers.requestFocus();
		      return;
          }

          // Instantiate the lotteryQuickPick object:
          lotteryQuickPick lqpObject = new lotteryQuickPick(intTotalNumbers, intTotalPicks);

          // Get Quick Pick numbers for the number of "Plays" on the ticket
          // the user requested. When outputting the Quick Pick numbers in the array
          // transforms it to a String horizontally.
          for (int intCount = 1; intCount <= intPlays; intCount++)
          {
			  sNumbers = "";
              iArrayQuickPicks = lqpObject.getQuickPicks();

              for (int intNumber : iArrayQuickPicks)
              {
                 sNumbers += intNumber + "  ";
              }  // end for each()

              writeMessage( "QP (" + intCount + "): " + sNumbers);

              //I added this line for testing purposes.  As you will see,
              //it returns false no matter what the results are, which is 
              //why I believe the problem lies in my call to the method.
              writeMessage( "Duplicates found: " + lqpObject.boolFound);

		  } // end for()

	   } // end actionPerformed

    } // end CreditCardButtonHandler


	// ClearButtonHandler click event
	private class ClearButtonHandler implements ActionListener
    {
     	public void actionPerformed(ActionEvent e)
      	{
			// Set to empty strings
			jtxtTotalNumbers.setText("");
			jtxtTotalNumbers.requestFocus();

			jtxtTotalPicks.setText("");
			jtxtPlays.setText("");

			jtaLotteryNumbers.setText("");

      	} // end actionPerformed

    } // end ClearButtonHandler


	// ExitButtonHandler click event
 	private class ExitButtonHandler implements ActionListener
    {
      	public void actionPerformed(ActionEvent e)
      	{
			System.exit(0);

      	} // end actionPerformed

    } // end ExitButtonHandler


    //******************
    //  Class Methods  *
    //******************

	// Main Method
    public static void main(String args[])
    {
		// Instantiate the JFrame
        lotteryQuickPickJFrame lotteryPicksJFrame = new lotteryQuickPickJFrame();

  	} // end main method


    private void writeMessage(String sMessageIn)
    {
	  jtaLotteryNumbers.append(sMessageIn + "\n");
    }

} // end creditCardJFrame Class



Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Method to check for duplicate number does not work

Posted 07 May 2012 - 08:20 PM

You have so many while() and reinitialization of your array it is very confusing

The easiest way to generate loto numbers is to fill an ArrayList with the possible numbers and randomly retreive from it

http://www.dreaminco...snippet2992.htm

It can also be done with a int[] with small modifications if you are not allowed to use ArrayList
Was This Post Helpful? 0
  • +
  • -

#6 MrsQ  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 20-September 08

Re: Method to check for duplicate number does not work

Posted 07 May 2012 - 08:39 PM

View Postpbl, on 07 May 2012 - 09:20 PM, said:

You have so many while() and reinitialization of your array it is very confusing

The easiest way to generate loto numbers is to fill an ArrayList with the possible numbers and randomly retreive from it

http://www.dreaminco...snippet2992.htm

It can also be done with a int[] with small modifications if you are not allowed to use ArrayList


More great code that I wish I could use, but unfortunately the 4 methods that I have coded are required for this assignment. (I was provided with main class along with the declarations of the 3 private methods and told what they should do. It was up to me to figure out what else I needed based on the main class, which is where I came up with the public method getQuickPicks(). Other requirements were No Number could be repeated in the Quick Pick Array and the Array must be sorted.

I realize that the nested while statements get a bit confusing, but I can't seem to figure out a better way to do it, considering the requirements that were set forth. Worse yet, they don't seem to be working :-(

Ah well, I will continue to play with it, perhaps an epiphany will hit me before sleep does...LOL

Thank you for looking and for your suggestions, while I can't use them in this project, I will keep them in mind for future use!
Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Method to check for duplicate number does not work

Posted 07 May 2012 - 08:59 PM

Try that a lot simpler
import java.util.*;
//Begin lotteryQuickPick class
public class lotteryQuickPick
{

	private int totalNumbersToPlay;
	private int[] pickArray;
	private Random ran;

	public lotteryQuickPick(int intTotNum, int intNumPicks)
	{
		ran = new Random();
		totalNumbersToPlay = intTotNum;
		pickArray = new int[intNumPicks];
	}


	//Method to check if a number has already been picked.
	private boolean numberUsed(int theNumber, int nbInUse)
	{

		for(int intIndex = 0; intIndex < nbInUse; intIndex++)
		{
			if(pickArray[intIndex] == theNumber)
				return true;
		}

		return false;

	}//end numberUsed method

	//method to return the requested Quick Pick number set to the screen
	public int[] getQuickPicks()
	{

		int intIndex = 0;

		while (intIndex < pickArray.length)
		{
			int num = ran.nextInt(totalNumbersToPlay) + 1;
			if(numberUsed(num, intIndex))
				continue;

			pickArray[intIndex++] = num;

		}

		//Next we sort the numbers:
		java.util.Arrays.sort(pickArray);

		//return the numbers in the array
		return pickArray;

	}//end getQuickPicks method

	public static void main(String[] arg) {
		lotteryQuickPick lqp = new lotteryQuickPick(20,5);

		for(int j = 0; j < 5; ++j) {
			System.out.println("test #" + j);

			int[] ar = lqp.getQuickPicks();
			for(int i = 0; i < ar.length; ++i)
				System.out.println(ar[i]);
		}
	}

}//End lotteryQuickPick class



Was This Post Helpful? 1
  • +
  • -

#8 MrsQ  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 20-September 08

Re: Method to check for duplicate number does not work

Posted 08 May 2012 - 09:50 PM

Unfortunately, I need to work with the helper class that I was given, so I cannot combine the main with my class and make them one. Also, when I was given the private methods, I was given the parameters to take in and what they should return, so I cannot change those either. I continue to play with this, but at this point, all that I've been able to figure out is that when I check for duplicates, the array is empty, and that is why it is not finding duplicates. This doesn't make sense because the array is returning Lottery Picks, so it can't be empty.

The problem seems to be in accessing the array to check for duplicates, but I cannot for the life of me see what I am doing wrong. I have gotten everything to work except the check for duplicates. I have tried numerous loops using examples that I have found (on this site and others) and nothing seems to work. I could be doing it wrong, or is it because of the method I must use to check for them? I also tried Arrays.binarySearch() with no luck. I have figured out that when I call the method and have it check the random number generated, it does not find any values stored in the array (at least as far as I can tell), so therefore, it never finds duplicates, but duplicates are output to the screen (in a pick 4, highest number 9, I will get numbers like 1 2 2 8, 1 1 6 6 , 3 3 3 2, etc…
So, I know what it’s not doing, I just don’t know why. The problem is clearly with my code, but after looking at it for 6 hours last night and another 4 tonight, I am still at a loss for where. If anyone can point me in the right direction, that would be great!
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Method to check for duplicate number does not work

Posted 09 May 2012 - 08:54 AM

View PostMrsQ, on 09 May 2012 - 12:50 AM, said:

Unfortunately, I need to work with the helper class that I was given, so I cannot combine the main with my class and make them one.

The main() I wrote was to test my code. Just delete it and use the main() of your tester

Quote

Also, when I was given the private methods, I was given the parameters to take in and what they should return, so I cannot change those either.

Just change them to use your own

Quote

I continue to play with this, but at this point, all that I've been able to figure out is that when I check for duplicates, the array is empty, and that is why it is not finding duplicates. This doesn't make sense because the array is returning Lottery Picks, so it can't be empty.
The problem seems to be in accessing the array to check for duplicates, but I cannot for the life of me see what I am doing wrong.

The big idea, that demonstrate my code, is to pass the number of already checked item to the method that checks for duplicates
Was This Post Helpful? 1
  • +
  • -

#10 MrsQ  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 20-September 08

Re: Method to check for duplicate number does not work

Posted 09 May 2012 - 12:00 PM

Thank you Paul! Your patience is so appreciated! Once I cleared my head (and code) of all the garbage I had going through it, I was able to see where you were coming from with your code. All is working wonderfully now, HUGE THANKS to you!!! :^: :^: :bananaman:
Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Method to check for duplicate number does not work

Posted 09 May 2012 - 12:24 PM

Glad I could help :^:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1