2

I am checking if number is between 1-10 using assert, but if I enter a number beyond 10 it still gives me the result rather than throwing an exception. What am I doing wrong?

import java.util.Scanner;

public class xina {
    public static void main(String[] args) throws Exception {

        System.out.println("enter any number");

        Scanner input = new Scanner(System.in);

        int num = input.nextInt();

        assert ( num >= 0 && num <= 10 ) : "bad number: " + num;
        System.out.println("You entered " + num);
    }
}
Chris Spittles
  • 15,023
  • 10
  • 61
  • 85
Nomad
  • 1,019
  • 4
  • 16
  • 30

3 Answers3

4

Assertions are disabled by default in java. You need to manually enable them by adding -ea to your command-line arguments when you invoke the java compiler. I can't tell you how to do this without knowing what compiler/environment you're using.

Edit:

In eclipse, go to the run menu, and click on run configurations. Select the arguments tab and type -ea into the VM arguments.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
1

Are assertions enabled (-ea flag when running program) ?

By default, they are not enabled by the virtual machine.

Baptiste Wicht
  • 7,472
  • 7
  • 45
  • 110
1

This article shows you how to do it in eclipse. Could be helpful for you

  • Go to Run->run configuration
  • select java application in left nav pan.
  • right click and select New.
  • select Arguments tab
  • Add -ea in VM arguments.

How to enable the Java keyword assert in Eclipse program-wise?

Community
  • 1
  • 1
Arno_Geismar
  • 2,296
  • 1
  • 15
  • 29