代码之家  ›  专栏  ›  技术社区  ›  Scruffy Nerfherder

需要处理堆栈数组的ArrayIndexOutOfBoundsException,无需程序结束

  •  0
  • Scruffy Nerfherder  · 技术社区  · 10 年前

    我正在做一个非常简单的程序,用户将被提示输入最多80个字符。我们需要构建自己的堆栈,并将每个字符推到堆栈上。然后弹出并以相反的顺序显示字符。我以为我完成了,但我的老师希望我在用户输入超过80个字符时做些什么。基本上,我需要忽略所有80岁以上的角色。我该怎么做呢?我一直在想办法解决这个问题,但没办法。我相信这将是我完全错过的简单的事情。感谢任何帮助和建议!

    堆栈用户 导入java.util.Scanner;

    public class stackUser {
    
    public static void main(String[] args){
        System.out.println("\nPlease enter up to 80 characters and I will reverse them: ");
        Scanner key = new Scanner(System.in);
        String input = key.nextLine();
        myStack stack = new myStack();
    
        for(int i = 0; i < input.length(); i++){
            char c = input.charAt(i);
            stack.push(c);
            }
    
        if(stack.isEmpty()){
            System.out.println("Stack is empty!");
        }else{
            while(!stack.isEmpty()){
                char rev = stack.pop();
                System.out.print(rev);
            }
         }  
       }
    }
    

    myStack(我的堆栈)

    public class myStack {
    
    private int max = 80;
    private char[] Stack = new char[max];
    private int top = -1;
    
    public void push(char input){
        top++;
        Stack[top] = input; 
        }
    
    public char pop(){
        char popped = Stack[top];   
        top --;
        return popped;
        }
    
    public boolean isEmpty(){
        boolean empty;
        if(top == -1){
            empty = true;
        }else{
            empty = false;
        }
        return empty;
        }
    }
    
    3 回复  |  直到 10 年前
        1
  •  2
  •   Vladislav Kievski    10 年前

    HandleArrayIndexOutOfBoundsException是个坏主意,您需要检查当前 top 具有的值 max 价值因为ArrayIndexOutOfBoundsException是未检查的异常,这意味着开发人员的错误。

        2
  •  1
  •   shofstetter    10 年前

    我将这样声明push方法,以表明如果达到最大值,它将抛出异常:

    public void push(char input) throws ArrayIndexOutOfBoundsException{
        top++;
        Stack[top] = input;
    }
    

    然后在main方法中,可以使用try/catch块来处理异常:

    try{
        stack.push(c);
    }catch (ArrayIndexOutOfBoundsException ex){
        System.out.println("too much!");
    }
    
        3
  •  0
  •   9Deuce user2989975    10 年前

    围绕任何将抛出IndexOutOfBounds的try-catch循环

    try {
            ...code here
    }
    catch (ArrayIndexOutOfBoundsException e) {
    
        ...whatever you want to do in event of exception
    
    } 
    
    推荐文章