-1

I was able to get the code to work and next challenge is to put it in a loop to work multiple times and loop should end if user enters -ve number or a 0. I am a complete beginner and please don't curse me for stupid code.

package Exceptions;

import java.util.Scanner;

public class usrDefined {

    public static void main(String[] args) {

        try {
            String s;
            int i;
            Scanner a = new Scanner(System.in);
            System.out.print("Enter your Name: ");
            s = a.nextLine();
            System.out.print("Enter your Age: ");
            i = a.nextInt();
            while((i = a.nextInt())!= -(i = a.nextInt()) && (i = a.nextInt())!= 0 ) 
            if (i < 18) {
                throw new AgeException();
            } 
            System.out.print("You are eligible for the deal " + s);
        } catch (AgeException e) {
            e.specifyException();

        }
    }
}

class AgeException extends Exception {
    public void specifyException() {
        System.out.println("Sorry,you are not eligible");
    }

}
  • 2
    `throw new AgeException();` - why? – Maroun Feb 06 '15 at 20:17
  • 2
    Does it even compile? What do you mean by `if ((a.nextInt) > 18);`? – Maroun Feb 06 '15 at 20:18
  • 1
    Why don't you tell us what's wrong first? You're claiming something is going wrong but not bothering to mention what it is. Also, it appears as though you're throwing an exception when you should just be using an if statement. Exceptions are for *exceptional behavior*. – tnw Feb 06 '15 at 20:18
  • See: http://stackoverflow.com/questions/3213094/when-to-use-exceptions-in-java-example – Morrison Chang Feb 06 '15 at 20:19
  • As @MarounMaroun says, `a` cannot be accessed in the `AgeException` class. – imtheman Feb 06 '15 at 20:21
  • I am newbie, so sorry I write some stupid code: @Maroun Maroun: throw new AgeException(); is to create new object. – Todd Goodfellow Feb 06 '15 at 20:27

4 Answers4

2

I'm not sure what that exception is meant to accomplish or why that was even attempted. If you're just looking to check if a value is less than 18, you can do that with a simple if statement:

String s;
int i;
Scanner a = new Scanner(System.in);
System.out.println("Enter your Name: ");
s = a.nextLine();
System.out.println("Enter your Age: ");
i = a.nextInt();

if (i < 18) {
    System.out.println("Sorry,you are not eligible");
    // presumably exit the application here as well?
} else {
    System.out.println("You are eligible for the deal!!!");
    // presumably continue with other logic here as well?
}

As a general rule, never use exceptions for logic flow. Conditional constructs (if statements, generally) exist for that purpose. An exception should be used to exit a method or operation in a faulted state so that the code consuming that method or operation can respond to that faulted state. Checking the age of the user isn't a faulted state, it's simply business logic.


As for why the code you have "doesn't work", there are a couple of issues...

This line will exit the code block immediately:

throw new AgeException();

This is because it, well, throws an exception. So nothing after that line will execute. The code will immediately go to the catch block, so the behavior to expect here would be that the user is never prompted for input and always immediately told that they are eligible for the deal.

Additionally, there are three errors here:

if ((a.nextInt) > 18);

The first error is that there is no a variable in that context. That variable is in the main method. So it would need to be passed to that specifyException method to use it.

The second error is that semi-colon. Unless the compiler complains about it syntactically (I'm not familiar enough with Java to know for certain) that will basically render the entire if block moot because it represents an empty statement. So the whole block translates to "if the value is greater than 18, do nothing".

The third error is that you forgot the parentheses for nextInt().

Finally, even if you don't immediately throw the exception, nowhere do you call the specifyException method. So that logic will never be invoked. If it seems unintuitive as to where or how you'd call that method, that's because it's on an exception and using exceptions for logic flow is inherently unintuitive and wrong :)

David
  • 208,112
  • 36
  • 198
  • 279
2

That's not how exception works. When you throw an exception, the exception condition has already occurred; you are reporting it. So, with this code, you are automatically generating the exceptional condition as soon as you enter the try block. Also, the condition isn't specified in a special specifyException method in the exception class definition. Plus, when you catch the exception, that is when the exception condition is handled, not when the exception condition did not occur.

To get this working with your AgeException:

  1. Remove that throw statement at the top.
  2. Once you have captured the age from the user input, then test the age with a normal if condition. Inside that if block, throw an instance of your AgeException.
  3. After the if block, but still in the try block, print your "you are eligible" message. If the exception wasn't thrown, the user is "eligible".
  4. When catching the exception, print the "not eligible" message.

However, using exceptions here doesn't seem right. Having someone's age be less than 18 doesn't seem like an exceptional condition to me. A simple if/else is a better design here.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Throwing an exception is not needed or good design. I think this is what you want:

 public static void main(String[] args) {
     Scanner a = new Scanner(System.in);
     System.out.println("Enter your Name: ");
     String s = a.nextLine();
     System.out.println("Enter your Age: ");
     int i = a.nextInt();
     if (ageOk(a)) {
         System.out.println("You are eligible for the deal!!!");
     }
}

private static boolean ageOk(int age) {
     return age > 18;
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

I am not sure if handleing this using exceptions is correct but you can try this:

UsrDefined.java

package exceptions;

import java.util.Scanner;

public class UsrDefined {



    public static void main(String[] args) {

    try{
         System.out.print("Enter your age:"); 
         Scanner a = new Scanner(System.in);
         checkAge(a);
    }catch (AgeException e){
         System.out.println(e.getMessage());
    }
}
    private static void checkAge(Scanner a) throws AgeException {

        if(a.nextInt() < 18) {
            throw new AgeException("You are not eligible for the deal!");
             }

    }


}

AgeException.java

package exceptions;

public class AgeException extends Exception {

    private static final long serialVersionUID = 1L;

    public AgeException(String msg) {
        super(msg);
    }

}
Andrei Puf
  • 81
  • 9
  • throw new AgeException("You are not eligible for the deal!"); No enclosing instance of type UsrDefined is accessible. Must qualify the allocation with an enclosing instance of type UsrDefined (e.g. x.new A() where x is an instance of UsrDefined). – Todd Goodfellow Feb 06 '15 at 21:21