Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs up Simple Java Program Help

    Hey guys,

    Here's the program.




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

    public class HighLowGame
    {
    public static void main(String[] args)
    {

    Random rand = new Random();


    int numberOfTries = 0;
    Scanner input = new Scanner(System.in);
    char repeat;
    char ans;
    int guess;
    boolean win = false;



    do {

    System.out.println("Pick a number between 0 and 10: ");
    guess = input.nextInt();
    numberOfTries++;
    int numberToGuess = rand.nextInt(10);

    if (guess == numberToGuess) {
    win = true;
    System.out.println("Congratulations you have won!");


    }
    else if (guess > numberToGuess) {
    System.out.println("Your guess was high try again");

    }
    else if (guess < numberToGuess) {
    System.out.println("Your guess was low try again");
    }

    System.out.println("The number was " + numberToGuess);
    System.out.println("You guessed the number in "+ numberOfTries + " attempt(s)");
    System.out.println("New game? 1 for Yes, or any other number to quit ");
    ans = input.next().charAt(0);

    } while (ans == 1);








    }
    }





    Two questions, why doesn't my program let me keep putting in numbers until I guess the right one?

    What is wrong with my loop? Pressing 1 should repeat the program, any other number should close.

    Thanks!

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    This is the JavaSCRIPT forum.

    About the only thing that Java and JavaScript have in common is the first four letters of their names.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    But to answer your question: Because you only have ONE loop. The one that lets you play another game.

    You need another loop that keeps you in the same game until you have won.

    (Though you have a handful of other more minor errors.)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •