首页 > 解决方案 > 即使捕获错误 ArrayIndexOutOfBounds 如何继续循环?

问题描述

如果 top==size,它会捕获一个错误并显示消息 Stack is full 而不会停止循环。如何做到这一点?但是我下面的代码不会停止

这是我的代码...

    while(ask==true){      
    try{
        String input=JOptionPane.showInputDialog("1.Push? Just type yes 2. Pop? just type no");
        if(input.equals("yes")){
            String element=JOptionPane.showInputDialog("Enter Element");
             int num=Integer.parseInt(element);
             top++;
          arr[top]=num;
             System.out.println("Insertion was successful:"+" "+arr[top]);
            // isFull();

        }else if(input.equals("no")){
            pop();

        }if(input.equals("exit")){
            getStack();
            top();
            ask=false;
        }
      }catch (ArrayIndexOutOfBoundsException e){
        System.out.println("full"); 
    }

}

标签: arraysstack

解决方案


while(ask==true) {
try {
    String input=JOptionPane.showInputDialog("1.Push? Just type yes 2. Pop? just type no");
    if (input.equals("yes")){
        String element=JOptionPane.showInputDialog("Enter Element");
        int num=Integer.parseInt(element);
        top++;
        if (top == size) throw new ArrayIndexOutOfBoundsException(); //solution
        arr[top]=num;
        System.out.println("Insertion was successful:"+" "+arr[top]);
        // isFull();

    } else if (input.equals("no")){
        pop();
    } if (input.equals("exit")){
        getStack();
        top();
        ask=false;
    }
} catch (ArrayIndexOutOfBoundsException e){
    System.out.println("full");
}

推荐阅读