randomguy537
randomguy537

Reputation: 205

How to enable assertions?

In my online Java programming class I have to write a program where the user enters their age, and checks if it's between 0 and 125 - if it isn't, it shows an error code, and I need to use assertions to do that. Here is my code:

import java.util.Scanner;

public class eproject1 {

   public static void main(String args[]) {

      Scanner input = new Scanner(System.in);

      System.out.print("What is your age? ");

      int num = input.nextInt();

      System.out.println(num);

      assert(num >= 1 && num < 125);

      System.out.printf("You entered %d\n", num); // NEED TO FIX, SOMETHING ISN'T RIGHT

   }

}

The problem is that it tells you what age you entered, even if it's out of the range 1 to 124. Research says that I need to actually enable assertions, but the results I found online were very unhelpful as they involved some Eclipse stuff - I'm sure it's some kind of rookie mistake, since i'm not very good at programming.

So ... how do you get the assertion stuff to work?

Upvotes: 15

Views: 20063

Answers (3)

Guildenstern
Guildenstern

Reputation: 3868

In my online Java programming class I have to write a program where the user enters their age, and checks if it's between 0 and 125 - if it isn't, it shows an error code, and I need to use assertions to do that.

The exercise is misguided.

Java assertions should never be used to implement error checking control flow.

Do not use assertions to do any work that your application requires for correct operation.
Because assertions may be disabled, programs must not assume that the boolean expression contained in an assertion will be evaluated. Violating this rule has dire consequences. For example, suppose you wanted to remove all of the null elements from a list names, and knew that the list contained one or more nulls. […]

A failed assertion should indicate a bug in your code. Supplying the wrong argument to a program is not a bug; it’s just a regular error.

Assertions are not needed to implement this kind of thing. Use some kind of exception if you want to crash the application on such a user error.

import java.util.Scanner;

public class eproject1 {

   public static void main(String args[]) {

      Scanner input = new Scanner(System.in);

      System.out.print("What is your age? ");

      int num = input.nextInt();
  
      System.out.println(num);

      if (!(num >= 1 && num < 125)) {
          throw new RuntimeException("Argument out of range");
      }

      System.out.printf("You entered %d\n", num);
   }

}

Upvotes: 5

Grotders
Grotders

Reputation: 9

run> edit configurations > modify options > Add VM options: input -ea to VM options

Upvotes: 0

nitishagar
nitishagar

Reputation: 9413

java -ea <program_name> should do it on the command prompt.

You can try the following for intellJ and eclipse respectively.

Upvotes: 30

Related Questions