educative.io

Educative

Project I: Guess the Right Number

hi, how i put condition to obligate the input user to be between 0 to 100?


Course: https://www.educative.io/collection/10370001/5317926874775552
Lesson: https://www.educative.io/collection/page/10370001/5317926874775552/6394932394196992

Hi @ayman, Thanks for reaching us for the feedback. If we look into the solution, we use the if conditional statement to validate the input. We can use a similar condition in the takeInput() function to obligate the input between 0 and 100, and if the value is not in this range, we can ask the user to enter the valid input. We can use the do-while loop to ask again and again until the user inputs the valid value.

We can add this condition to the solutions as follow:

public static int takeInput(int guess) {
    Scanner userInput = new Scanner(System.in);
    
    do {
        System.out.print("Enter a number between 0 to 100: ");

        if(userInput.hasNextInt()) {
            guess = userInput.nextInt(); 

            if(guess < 0 || guess > 100) {
                System.out.println("Your input is not in valid range.");
            } else {
                return guess;
            }
        } else {
            System.out.println("Enter a valid integer number between 0 and 100.");
            userInput.next();
        }
    } while(true);
}

In the above function, we used a do-while loop to get valid input from the user. We get the input and check if it is an integer or not. In the case of an integer value, we used another conditional statement to validate that the input value is between 0-100. If this condition is validated, we use the return statement to end the loop and return the value. In case of any condition fails, the do-while statement runs all steps again to get input from the user.

I hope you get how to obligate the input value. If you have any queries, please feel free to reach us. Thanks!

2 Likes

hi, thank you very much its very helpful your solution.


Course: https://www.educative.io/collection/10370001/5317926874775552
Lesson: https://www.educative.io/collection/page/10370001/5317926874775552/6644928498630656

2 Likes