【发布时间】: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