Search code examples
javaassert

Assert error in java


probably newbie error here. I copied the assert code directly from the book, but the AssertionError isn't being thrown. If I enter a value lower than 0or higher than 10 execution continues normally.

import java.util.Scanner;

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

        System.out.print("enter a number between 0 and 10: ");
        int number = scanner.nextInt();

        assert (number >= 0 && number <= 10) : "bad number: " + number;

        System.out.println("You entered " + number);
        scanner.close();
    }
}

enter a number between 0 and 10: -3
You entered -3

Solution

  • AssertionError isn't being thrown.

    Add -ea (enabling assertions) to the Java command arguments when running your application.