mercredi 12 septembre 2018

How to repeat if statements in while loops

I'm trying to have a user guess a number picked by a random number generator, but my code decides to, if it doesn't equal, stick within one if statement.

   System.out.println("Enter a guess between 1 and 200: ");
    String guess = input.nextLine();
    int userInput = Integer.parseInt(guess);

    Random rnd = new Random(seed);

    int x = rnd.nextInt(200) + 1;
    int currentInt = 1;
    String msg = "That was impossible!";

and my while loop contains many if statements:

boolean boo = false;
while (!boo) {

        if (userInput == x) {
            System.out.println("Congratulations! Your guess was correct!");
            System.out.println("");
            System.out.println("I had chosen " + x + " as the target number.");
            System.out.println("You guessed it in " + currentInt + " tries.");

            if (currentInt == 1) {
                //do something
            } else if (currentInt >= 2) {
                //do something
            } else if (currentInt >= 4) {
                ...
            } else if (currentInt >= 11) {
                msg = "Maybe you should play something else";
                System.out.println(msg);
            }
            break;
        } else if (userInput > x) {
            System.out.println("Your guess was too high - try again.");
            System.out.println("");
            System.out.println("Enter a guess between 1 and 200: ");
            String highGuess = input.nextLine();
            int tooHigh = Integer.parseInt(highGuess);
            continue;
        } else if (userInput < x) {
            System.out.println("Your guess was too low - try again.");
            System.out.println("");
            System.out.println("Enter a guess between 1 and 200: ");
            String lowGuess = input.nextLine();
            int tooLow = Integer.parseInt(lowGuess);
            continue;
        }
        currentInt = currentInt + 1;

    }

My code works decently, if the answer is correct in the first try then the first if statement works, but if it's greater or less than x, then the same block runs (if greater, keeps putting greater even if next input is less than)

Aucun commentaire:

Enregistrer un commentaire