我正在编写一个非常简单的程序,系统将提示用户输入最多 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;
}
}
最佳答案
处理 ArrayIndexOutOfBoundsException 是个坏主意,您需要使用 max
值检查当前的 top
值。因为ArrayIndexOutOfBoundsException是未经检查的异常,它意味着开发人员的错误。
关于java - 需要处理堆栈数组的ArrayIndexOutOfBoundsException,程序不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32466632/