-1

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
stumped
  • 3,235
  • 7
  • 43
  • 76
  • possible duplicate [how to enable java keyword assert in Eclipse in program wise?](http://stackoverflow.com/questions/11415160/how-to-enable-java-keyword-assert-in-eclipse-in-program-wise) – Reimeus Dec 25 '13 at 00:13
  • Don't use `assert` to validate user input since they're not guaranteed to run: http://stackoverflow.com/a/298973/20394 – Mike Samuel Dec 25 '13 at 00:15

2 Answers2

3

AssertionError isn't being thrown.

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

Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
1

You must run the program with assertions enabled.

java -ea[:<packagename>...|:<classname>]
adarshr
  • 61,315
  • 23
  • 138
  • 167