3

I made a quick program recently to have the computer guess a number you input. I was just using it to show a friend an example of a While loop. I decided I wish to make it more complicated but I'm not sure how to do it.

I wish to add each random guess to an array so that it doesn't guess the same number more than once.

Scanner scan = new Scanner (System.in); // Number to guess //
Random rand = new Random(); // Generates the guess //
int GuessNum = 0, RandGuess = 0;

System.out.println("Enter a number 1 - 100 for me to guess: ");
int input = scan.nextInt();

if (input >= 1 && input <= 100)
{
 int MyGuess = rand.nextInt (100) + 1;
   while ( MyGuess != input)
   {
     MyGuess = rand.nextInt (100) + 1;
     GuessNum++;
   }
   System.out.println ("I guessed the number after " + GuessNum + " tries.");
}
5
  • What don't you know how to do? Commented Nov 9, 2015 at 15:11
  • Rather than an array, consider a Set. This kind of situation ("has this value been encounter before") is a perfect match for it. Commented Nov 9, 2015 at 15:14
  • What efforts have you made so far? Commented Nov 9, 2015 at 15:15
  • I would make an array and index it by GuessNum, and I would have another while loop to check through all the results and see if they've already been done. Commented Nov 9, 2015 at 15:17
  • Sorry about that, I was out for the day. I appreciate the responses and I'm going to try and see what I can do! Commented Nov 10, 2015 at 14:21

6 Answers 6

6

You might want to use an ArrayList(A dynamically increasing array)

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(num);

If you want to see if that number is already added into the arraylist

if(list.contains(num))
{
 System.out.println("You already tried " + num);
}

A Set is also considerably better option. It is the same as a ArrayList but doesn't allow duplicates.

HashSet<Integer> set = new HashSet<Integer>();

set.add(num);//returns true if the num was not inserted before else return false

if(!set.add(num))//set also has a contains method
{
  System.out.println("You already entered " + num);
}
Sign up to request clarification or add additional context in comments.

1 Comment

new HashSet(); and new ArrayList(); create raw types. You should avoid raw types. Use diamond notation e.g. new HashSet<>();
3

A Set is an appropriate container for that functionality. You would define it like this :

Set<Integer> previous = new HashSet<>();

And to get a random number that you haven't previously tried

while (previous.contains(MyGuess))
    MyGuess = rand.nextInt(100) + 1;
previous.add(MyGuess);

This will get new random numbers from rand object until one is found that isn't in previous. Then that is added to previous for the next iteration.

Comments

3

Arrays in Java are of fixed size. Once you have allocated an array, adding elements is allowed only up to the number of elements that you have allocated upfront. This wouldn't be a big issue in your situation, because the values are limited to 100, but you have better alternatives:

Java library offers collections that grow dynamically. In your case a HashSet<Integer> would be a good choice:

  • HashSet can grow to an arbitrary size as you go
  • Checking HashSet for a number is a quick operation

Another solution would be to make an array of 101 booleans:

boolean[] seen = new boolean[101];

Now you can check if the number has been seen before by testing seen[myGuess] to be false, and set seen[myGuess] = true when you see a new number. This approach is also very fast. However, you need to keep track of how many available numbers you have, because the range from 1 to 100 will get exhausted after 100 guesses, so trying to generate an additional number would become an infinite loop.

2 Comments

ArrayList is not fixed in size.
@MuratK. What does ArrayList have to do with my answer?
2

Use a HashSet<Integer> to do this. The values in a Set are unique so this is an easy way to store the already guessed values.

The contains(...) method is how you find out if you've guessed this number before

Comments

2

A very simple example would be:

public static int[] randomArray(){
    int number = Integer.parseInt(JOptionPane.showInputDialog("How many numbers would you like to save?: "));       //Get Number of numbers from user
    int[] array = new int[number];  //Create the array with number of numbers (by User)
    for(int counter = 0; counter < number; counter++){      //For loop to get a new input and output every time
        int arrayString = (int) (Math.random() * 10);
        array[counter] = arrayString;
        System.out.println("Number " + (counter + 1) + " is: " + array[counter]);   //Print out the number
    }
    return array;
}

This example adds numbers every time the loop repeats, just replace the random with the number you want.

Comments

1

The easiest way would be to add an ArrayList and just to check if the list contains the random value:

Ar first you make and new ArrayList:

ArrayList<Integer> myGuesses = new ArrayList();

The second step is to add the random value to the list:

ArrayList<Integer> myGuesses = new ArrayList();

Now you only have to check if if the List cotains the value bevore generating a new one and counting your trys:

if(myGuesses.contains(MyGuess))
{
   //your code
}

I applied this to your code:

Scanner scan = new Scanner(System.in); // Number to guess //
        Random rand = new Random(); // Generates the guess //
        int GuessNum = 0, RandGuess = 0;
        ArrayList<Integer> myGuesses = new ArrayList();

        System.out.println("Enter a number 1 - 100 for me to guess: ");
        int input = scan.nextInt();

        if (input >= 1 && input <= 100) {
            int MyGuess = rand.nextInt(100) + 1;
            while (MyGuess != input) {

                if(myGuesses.contains(MyGuess))
                {
                    MyGuess = rand.nextInt(100) + 1;
                    GuessNum++;
                    myGuesses.add(MyGuess);
                }
            }
            System.out.println("I guessed the number after " + GuessNum + " tries.");
        }

I hope that helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.