arrays - 即使捕获错误 ArrayIndexOutOfBounds 如何继续循环?
问题描述
如果 top==size,它会捕获一个错误并显示消息 Stack is full 而不会停止循环。如何做到这一点?但是我下面的代码不会停止
这是我的代码...
while(ask==true){
try{
String input=JOptionPane.showInputDialog("1.Push? Just type yes 2. Pop? just type no");
if(input.equals("yes")){
String element=JOptionPane.showInputDialog("Enter Element");
int num=Integer.parseInt(element);
top++;
arr[top]=num;
System.out.println("Insertion was successful:"+" "+arr[top]);
// isFull();
}else if(input.equals("no")){
pop();
}if(input.equals("exit")){
getStack();
top();
ask=false;
}
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("full");
}
}
解决方案
while(ask==true) {
try {
String input=JOptionPane.showInputDialog("1.Push? Just type yes 2. Pop? just type no");
if (input.equals("yes")){
String element=JOptionPane.showInputDialog("Enter Element");
int num=Integer.parseInt(element);
top++;
if (top == size) throw new ArrayIndexOutOfBoundsException(); //solution
arr[top]=num;
System.out.println("Insertion was successful:"+" "+arr[top]);
// isFull();
} else if (input.equals("no")){
pop();
} if (input.equals("exit")){
getStack();
top();
ask=false;
}
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("full");
}
推荐阅读
- python - Python – 在无缓冲的标准输入上选择
- javascript - 如何让 document.getElementsByTagName('').innerHTML 在 2 个标签之间生成文本?
- youtube - 查找带有字幕的特定语言的随机 youtube 视频
- unit-testing - 颤振:比较两个对象并得到错误:预期:VenuesDetails:
在单元测试中 - python - 如何在数据帧上使用 def-return 或 for-in 语句来避免 python /pandas 中的代码重复
- python - 使用 conda 在 Elastic Beanstalk 上安装 python 模块
- git - 我可以在现有提交下进行 git 提交而不在下一次提交中保留其任何内容吗?(只是为了让代码成为历史)
- sql - 如何在同一行中返回每周轮班开始和结束预定时间?
- python - 如何让 python 识别字符串中的正确子字符串?
- python - PyQt5:如何使用计时器每秒增加一个变量?