【发布时间】:2013-12-31 16:09:49
【问题描述】:
我正在练习 Try-Catch、异常处理以及堆栈和队列,所以虽然代码可能不切实际,但它对我的练习很有用。
public class Practice {
public static void main(String args[]){
Stack<String> sStack = new Stack<String>();
Queue<String> sQueue = new LinkedList<String>();
Scanner input = new Scanner(System.in);
String inString = " ";
boolean done = false;
do{
try{
while(!inString.equals("")){
System.out.println("Enter a string: ");
inString = input.nextLine().toString();
addS(sStack,inString);
}
done = true;
}catch(Exception e){}
sStack.pop();
for(int i = 0; i<sStack.size()+1;i++){
remS(sStack);
}
}while(done == false);
}
该代码旨在根据用户输入循环并填充一个空堆栈,然后循环通过堆栈并在给出提示时删除每个元素。我输入的第一组是:
[艺术,蝙蝠,猫,码头,眼睛,父亲]
第二组是:
[艺术,蝙蝠,猫,码头,眼睛,父亲,孩子]
我注意到,无论我输入多少元素,它最多只能删除 4 个元素。我想请你帮忙找出原因。如您所见,我尝试使用循环的边界,但无济于事。无论我从哪里开始或绑定,它总是会弹出最多 4 个元素。
下面我提供的addS和remS函数
public static void addS(Stack t, String s){
t.push(s);
System.out.printf("%s was added to the stack %s", s, t);
System.out.println();
}
public static void remS(Stack t){
System.out.printf("\n%s has been popped.",t);
t.pop();
System.out.printf("The current elements are now: ");
System.out.print(t);
System.out.printf("The next element to be popped is %s", t.peek());
}
【问题讨论】:
标签: java exception-handling stack queue try-catch