Input Validation

Report a typo

Here is a program that takes a positive integer as input and calculates its square. However, users may input any other number, so it is essential to implement a validation check. If the input is incorrect, the user should be prompted to enter a valid number again.

Fill in the gaps with the relevant elements
import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while () {
            System.out.print("Enter a positive number: ");
            int userInput = scanner.nextInt();

            if (userInput <= 0) {
                System.out.println("Invalid input. Please enter a positive number.");
                ;
            }

            System.out.println(userInput * userInput);
            ;
        }
    }
}
continuetruefalsebreak

Create a free account to access the full topic