Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat "if" statement when output is false

I am working on a simple game in which the user has to guess a random number. I have all the code set up except for that fact that if the guess is too high or too low I don't know how to allow them to re-enter a number and keep playing until they get it. It just stops; here is the code:

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

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();

        int random = rand.nextInt(10) + 1;

        System.out.print("Pick a number 1-10: ");
        int number = input.nextInt();

        if (number == random) {
            System.out.println("Good!");
        } else if (number > random) {
            System.out.println("Too Big");
        } else if (number < random) {
            System.out.println("Too Small");
        }
    }
}
like image 558
Trevn Jones Avatar asked Sep 25 '15 00:09

Trevn Jones


1 Answers

In order to repeat anything you need a loop.

A common way of repeating until a condition in the middle of loop's body is satisfied is building an infinite loop, and adding a way to break out of it.

Idiomatic way of making an infinite loop in Java is while(true):

while (true) {
    System.out.print("Pick a number 1-10: ");
    int number = input.nextInt();
    if (number == random) {
        System.out.println("Good!");
        break; // This ends the loop
    } else if (number > random) {
        System.out.println("Too Big");
    } else if (number < random) {
        System.out.println("Too Small");
    }
}

This loop will continue its iterations until the code path reaches the break statement.

like image 191
Sergey Kalinichenko Avatar answered Oct 29 '22 15:10

Sergey Kalinichenko