中断class Main,如果方法returns "false"

interrupt class Main, if the method returns "false"

我想在我的抽象 ATM 中冻结一张卡。

以这种方式,如果在第三次尝试后 PIN 仍未被接受,我需要中断程序,以便 Main class 不会执行下一个方法。


它是 System.exit(0) 最优决策吗?我选择这个是因为它很简单,但我不确定。

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 主要是这样的:

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(); 
}

您可以试试下面的代码:

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

main方法中:

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());
    }
}

yourException class:

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