【问题标题】:Need to handle ArrayIndexOutOfBoundsException for stack array, without program ending需要处理堆栈数组的ArrayIndexOutOfBoundsException,没有程序结束
【发布时间】:2015-12-04 15:50:31
【问题描述】:

我正在做一个非常简单的程序,系统会提示用户输入最多 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);
        }
     }  
   }
}

我的堆栈

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

【问题讨论】:

    标签: java exception data-structures stack indexoutofboundsexception


    【解决方案1】:

    处理 ArrayIndexOutOfBoundsException 是个坏主意,您需要检查当前的 top 值和 max 值。因为 ArrayIndexOutOfBoundsException 是未经检查的异常,是开发者的错误。

    【讨论】:

    • 我想在哪里检查这些值?我想忽略超过max 的每个字符。所以我一直在尝试while(top &lt;= max) 在我的push 方法中只将前80 个推入堆栈。但这不起作用。
    • 你可以这样写:public void push(char input) { if (top &lt; max - 1) { top++; Stack[top] = input; } }
    • 效果很好!我正在尝试类似的东西,但完全忘记了 max 的 -1 谢谢!
    【解决方案2】:

    我会这样声明 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】:

      任何会抛出 IndexOutOfBounds 的东西的 try catch 循环

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多