如何处理不会导致错误的 emptycollectionsException?

huangapple go评论69阅读模式
英文:

How to handle a emptycollectionsException that doesn't result in an error?

问题

今天我有一个关于代码中的EmptyCollectionException的问题。以下是重要部分:

public static void main (String [] args) //程序的主类
{
    Scanner input = new Scanner(System.in);
    ArrayStack<String> stk = new ArrayStack<String>();
    int menu = 0; //初始化菜单
    do {
        System.out.println("堆栈菜单选项\n1.入栈 \n2.出栈 \n3.查看栈顶元素 \n4.显示栈 \n5.退出");
        System.out.println();
        System.out.print("请输入您的选择:");
        menu = Integer.parseInt(input.next()); //允许用户输入选择。
        switch (menu) {
            case 1: //如果选择了1,则用户可以将元素入栈。
                System.out.print("请输入元素:");
                String element = input.next();
                stk.push(element);
                break;
            case 2: //如果选择了2,则从栈顶弹出元素。
                System.out.println("弹出的元素为:" + stk.pop());
                break;
            case 3: //如果选择了3,则查看栈顶元素但不删除。
                System.out.println("栈顶元素为:" + stk.peek());
                break;
            case 4: //如果选择了4,则显示整个栈。
                System.out.println("完整的栈为:\n" + stk);
                break;
            default:
                System.out.println("选择了退出,程序正在关闭。"); //关闭程序
                return;
        }
    } while (true); //只要输入了1-5,程序就会循环。
}

我遇到的错误是,当我尝试从空栈执行“出栈”操作时,会出现以下错误:

堆栈菜单选项
1.入栈 
2.出栈 
3.查看栈顶元素 
4.显示栈 
5.退出

请输入您的选择:2
Exception in thread "main" jsjf.exceptions.EmptyCollectionException: 栈为空。
	at jsjf.ArrayStack.pop(ArrayStack.java:57)
	at jsjf.ArrayTest.main(ArrayTest.java:39)
C:\Users\ADAIS\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java 返回了:1
构建失败(总时间:3秒)

我知道是什么导致了这个错误,是Pop和Peek代码在使用EmptyCollectionException类:

public T pop() throws EmptyCollectionException //从栈顶移除元素并返回引用。如果栈为空,则抛出EmptyStackException。
{
    if (isEmpty())
        throw new EmptyCollectionException("stack");
    top--;
    T result = stack[top];
    stack[top] = null;
    return result;
}

public T peek() throws EmptyCollectionException //返回栈顶元素的引用。不从栈顶移除元素。如果栈为空,则抛出EmptyCollectionException。
{
    if (isEmpty())  
        throw new EmptyCollectionException("stack");
    return stack[top-1];
}

而EmptyCollectionException类是这样的:

public EmptyCollectionException(String collection)
{
    super("The " + collection + " is empty.");
}

我想知道是否有人知道如何使它不会崩溃,而是循环显示“栈为空,请重试”之类的消息?这个代码的任务已经完成了,我只是想为了自己而修复它。

英文:

Today I have a question regarding the emptycollectionsException in my code. Here's the important bits

public static void main (String [] args) //Main class of the program
{
Scanner input = new Scanner(System.in);
ArrayStack&lt;String&gt; stk = new ArrayStack&lt;String&gt;();
int menu = 0; //Initializes menu
do {
System.out.println(&quot;Stack Menu Selections\n1.Push \n2.Pop \n3.Peek \n4.Display \n5.Exit&quot;);
System.out.println();
System.out.print(&quot;Enter your Choice: &quot;);
menu =Integer.parseInt(input.next()); //Allows the user to input a selection.
switch (menu) {
case 1: //If 1 is selected then the user can push an element into the stack.
System.out.print(&quot;Enter element: &quot;);
String element = input.next();
stk.push(element);
break;
case 2: //If 2 is selected then the element at the top is popped from the stack. 
System.out.println(&quot;Popped Element is &quot; + stk.pop());
break;
case 3: //If 3 is selected then the top element is peeked but not deleted.
System.out.println(&quot;Peeking is &quot; + stk.peek());
break;
case 4: //If 4 is selected, then the full stack is displayed.
System.out.println(&quot;Full Stack is: \n&quot; + stk);
break;
default: System.out.println(&quot;Exit selected, shutting down program.&quot;); //Closes program
return;
}
}while(true); //Program loops as long as 1-5 are inputed.
}

The error I'm facing is that when I go to "pop" an empty stack, it results in this

Stack Menu Selections
1.Push 
2.Pop 
3.Peek 
4.Display 
5.Exit
Enter your Choice: 2
Exception in thread &quot;main&quot; jsjf.exceptions.EmptyCollectionException: The stack is empty.
at jsjf.ArrayStack.pop(ArrayStack.java:57)
at jsjf.ArrayTest.main(ArrayTest.java:39)
C:\Users\ADAIS\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)

I know what's causing it, an EmptyCollectionsException class that the Pop and Peek code is using

public T pop() throws EmptyCollectionException //Removes the element that&#39;s at the top
//of the stack and returns with a reference
//to it. Throws an EmptyStackException if the
//stack is empty
{
if (isEmpty())
throw new EmptyCollectionException(&quot;stack&quot;);
top--;
T result = stack[top];
stack[top] = null;
return result;
}
public T peek() throws EmptyCollectionException //Returns a reference to the element that&#39;s
//at the top of the stack. The element is 
//not removed from the top of the stack.
//throws an EmptycollectionException is the stack is empty
{
if (isEmpty())  
throw new EmptyCollectionException(&quot;stack&quot;);
return stack[top-1];
}

which is

public EmptyCollectionException(String collection)
{
super(&quot;The &quot; + collection + &quot; is empty.&quot;);
}

I was wondering if anyone had any breadcrumbs on how to make it so that instead of crashing, it loops with a "Stack is empty, try again" kinda thing? The assignment for this code is already finished, I just wanna fix it for my own sake.

答案1

得分: 0

  1. 在调用 pop() 之前检查 isEmpty()。

  1. 处理异常:
        do { 
try { 
switch (…) { 
….blah blah blah … 
} 
}
catch (EmptyCollectionException ex) { 
System.out.println("Nothing to pop"); 
} 
} while (true);
英文:
  1. Check isEmpty() before calling pop()

or

  1. Handle the exception:

    do { 
    try { 
    switch (…) { 
    ….blah blah blah … 
    } 
    }
    catch (EmptyCollectionException ex) { 
    System.out.println(&quot;Nothing to pop&quot;); 
    } 
    } while (true);   
    

huangapple
  • 本文由 发表于 2020年9月12日 22:10:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63861180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定