首页 > 解决方案 > 如何在不返回值的情况下显示消息

问题描述

在这个函数中,如果 isEmpty ,我不想返回 0 或任何数值..我只想在我从 main 出队时显示消息。我如何通过处理此自定义消息或任何其他方式的异常来做到这一点?

public int dequeue()
    {
        if(this.isEmpty()){
            System.out.println("Queue is Empty !"); 
            return 0;
        }
        else{ 
            first++; 
            int x = arr[first]; 
            return x;
        }
    }

标签: javaexceptiondata-structuresqueue

解决方案


public int dequeue() throws ArrayIndexOutOfBoundsException
{
    first++; 
    int x = arr[first]; 
    return x;
}

当你调用它时:

try {
    dequeue();
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Queue is empty!");
}

推荐阅读