jeudi 19 septembre 2019

Stack Overflow on Random Integers

Where the commented section is, it says that there is a Stack Overflow Error - null. I am trying to get it to make random numbers to match up with an inputted value. The goal of this code is to do the following:

  1. Accept a top number (ie 1000 in order to have a scale of (1-1000)).
  2. Accept an input as the number for the computer to guess.
  3. Computer randomly guesses the first number and checks to see if it is correct.
  4. If it is not correct, it should go through a loop and randomly guess numbers, adding them to an ArrayList, until it guesses the input. It should check to see if the guess is already in the array and will generate another random number until it makes one that isn't in the list.
  5. In the end, it will print out the amount of iterations with the count variable.

Code:

import java.util.*;

public class ArrNumGuess
{
    public static Integer top, input, guess, count;
    public static ArrayList <Integer> nums;
    public static void main ()
     {
        System.out.println("Please enter the top number");
        top = (new Scanner(System.in)).nextInt();
        System.out.println("Please enter the number to guess (1 - " + top + ")");
        input = Integer.parseInt(((new Scanner(System.in)).nextLine()).trim());
        nums = new ArrayList<Integer>(); //use nums.contains(guess);
        guess = (new Random()).nextInt(top) + 1;
        nums.add(guess);
        System.out.println("My first guess is " + guess);
        count = 1;
        if(guess != input)
        {
            guesser();
        }
        System.out.println("It took me " + count + " tries to find " + guess + " and " + input);
    }

    public static void guesser()
    {
         boolean check = false;
         while(!check)
        {
            guess = (new Random()).nextInt(top) + 1; //Stack Overflow - null
            if(nums.contains(guess) && !(guess.equals(input)))
            {
                count--;
                guesser();
            }
           else if(guess.equals(input))
           {
                check = true;
                System.out.println("My guess was " + guess);
                // nums.add(guess);
                count++;
            }
           else
           {
               System.out.println("My guess was " + guess);
                nums.add(guess);
                count++;
           }
        }
     }
 }




Aucun commentaire:

Enregistrer un commentaire