how to not allow a user to enter a mark greater than 100 or below 0 in java

www.lautt‮moc.iru‬
how to not allow a user to enter a mark greater than 100 or below 0 in java

To prevent a user from entering a mark greater than 100 or below 0 in Java, you can use a loop and a condition to validate the input.

Here is an example of how you can validate the input and prevent a user from entering a mark greater than 100 or below 0 in Java:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int mark = 0;
        while (mark < 0 || mark > 100) {
            System.out.print("Enter a mark between 0 and 100: ");
            mark = scanner.nextInt();
            if (mark < 0 || mark > 100) {
                System.out.println("Invalid mark. Please try again.");
            }
        }
        
        System.out.println("Mark: " + mark);
    }
}

In this example, a Scanner object is created to read the input from the user. A loop is used to keep asking for the mark until a valid mark between 0 and 100 is entered. The input is read using the nextInt method of the Scanner class and validated using an if statement. If the input is invalid, a message is displayed to the user, and the loop continues. When a valid mark is entered, the loop exits and the mark is printed to the console.

Keep in mind that this is just one way to validate the input and prevent a user from entering a mark greater than 100 or below 0 in Java. You can use different methods and techniques to achieve the same result.

Created Time:2017-11-01 20:42:58  Author:lautturi