interrupt class Main, if the method returns "false"

时间:2015-06-25 18:14:41

标签: java exit break

I would like to block a Card in my abstract ATM.

At this manner, I need to interrupt the program if the PIN wasn't accepted after the third attempt so that the Main class won't execute the next Methods.


Is it System.exit(0) the optimal decision? I chose this one because it's simple, but I'm not sure.

public boolean authenticity(int tries) {
                if (tries <= 3)
                {
                    short pin = sc.nextShort();
                    if (pin == 1234) {
                        System.out.println("PIN is correct");
                        System.out.println("Card is active for operation!");
                        return true;
                    } else {
                        System.out.println("PIN isn't correct! You used " + tries +" attempt!");
                        return authenticity(++tries);
                    }
                }
                System.out.println("\nCard was blocked!");
                System.exit(0);
                return false;
            }

class Main looks so:

public class Main {
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        ATM atm = new ATM();
        MasterCard aeroflotCard = new MasterCard();
        atm.initCard(aeroflotCard);

        aeroflotCard.authenticity(1);  // if pin is wrong, than you are looser:)
        System.out.println("\nRefill your balance:");
        aeroflotCard.add(sc.nextInt());
        aeroflotCard.balance(); 
}

1 个答案:

答案 0 :(得分:1)

You may try the following piece of code:

public boolean authenticity(int tries) throws yourException {
    if (tries <= 3) {
        // ...
    } else {
         throw new yourException("\nCard was blocked!");      
    }
}

In the main method:

public static void main(String[] args) {
    try {
            aeroflotCard.authenticity(1);
            System.out.println("\nRefill your balance:");
            aeroflotCard.add(sc.nextInt());
            aeroflotCard.balance(); 
    } catch (yourException e) {
            System.err.println(e.getMessage());
    }
}

In the yourException class:

public class yourException extends Exception {
// here you can override needed methods
}