Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Jennifer Barbee
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Barbee
Front End Web Development Techdegree Student 2,387 Points

How come when a user guesses a random number... they have to guess it twice to be caught?

Please help, I've been stuck on this project for over two weeks. How come my random number generator won't produce a number between 1 and the max number? Right now it includes 0. Also, sometimes the user has to guess a number two times before the loop catches it. What am I doing wrong here? I have to run it a couple times to catch the errors because sometimes it appears to run fine depending on the random number.

import java.util.Scanner;

public class GuessingGame {
    public static void main(String[] args) {
      System.out.println("ADMINISTRATOR SETUP\n********************");

      System.out.println("GUESSING GAME: Guess how many items are in the jar.\n\nSelect the type of items, and how many can reasonably fit in a jar.\nSound good?  Okay let's begin!\n");
      if(args.length != 2) {
        Jar jar = new Jar();
        jar.fillJar();
      }



    }
    }
import java.util.Scanner;
import java.util.Random;


public class Jar {
  private String itemName;
  public int maxItems;


public Jar() {
  Scanner scanner = new Scanner(System.in);
  System.out.println("What type of item?");
  this.itemName = scanner.nextLine();
  System.out.println("What is the maximum amount of " + itemName + " ?");
  this.maxItems = Integer.parseInt(scanner.nextLine());

  System.out.println("\nPLAYER\n********************\nHow many " + itemName + " are in the jar?\nPick a number between 1 and " + maxItems);

}
  public String fillJar() {

    Random randomNumber = new Random();
    int rand = randomNumber.nextInt(this.maxItems/2+1);


    Scanner scanner = new Scanner(System.in);
    int guess = Integer.parseInt(scanner.nextLine());

    int count = 1;
    do {
      Scanner scanner1 = new Scanner(System.in);
      System.out.println("\nHow many " + itemName + " are in the jar?  Pick a number between 1 and " + maxItems);
       guess = Integer.parseInt(scanner1.nextLine());
       count ++;
       if(guess==rand){
         System.out.println("You got it in " + count + " attempt(s)");
      }

      } while(guess != rand);  
    return "You got it in X attempt(s)";

    } 
}