Java – how to repeat the “if” statement when the output is false

I'm developing a simple game where users have to guess a random number I've set up all the code except the fact that if the guess is too high or too low, I don't know how to allow them to re-enter the number and continue playing until they get it It just stops; This 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");
        }
    }
}

Solution

In order to repeat anything, you need a cycle

A common way to repeat until the conditions in the middle of the loop body are met. Build an infinite loop and add a method to break through it

The usual method to create 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 continues its iteration until the code path reaches the break statement

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>