Checking with assert that a value is within range. - Java Language Basics

Java examples for Language Basics:assert

Description

Checking with assert that a value is within range.

Demo Code

import java.util.Scanner;

public class Main
{
   public static void main(String[] args)
   {/*from ww  w  .  j  av a2 s  . com*/
      Scanner input = new Scanner(System.in);
      
      System.out.print("Enter a number between 0 and 10: ");
      int number = input.nextInt();
      
      // assert that the value is >= 0 and <= 10
      assert (number >= 0 && number <= 10) : "bad number: " + number;
      
      System.out.printf("You entered %d%n", number);
   } 
}

Result


Related Tutorials