根据条件从方法返回bool或整数

时间:2014-02-04 15:33:05

标签: java return

pop 非常基本的程序来自DS中的Stack:

public int pop()
{
    if(!isEmpty())
    {
        int pop_val = myArray[topIndex];
        topIndex--;
        return pop_val;
    }
    else
    {
        System.out.println("Stack is empty");
        System.exit(0); /* stop the program execution*/
        return 4; /* did this just to avoid the error*/
    }
}

问题:正如您所看到的,方法应返回int类型值我只想打印或返回false,如果堆栈是空。

问题:

  • 是否可以在java中返回不同类型的返回值 根据条件???以及

  • 有没有更好的解决方法来解决此问题,而不是我在我的代码中尝试的内容?


P.S: 在回答之前请不要继续使用我的代表,在java

Noob

4 个答案:

答案 0 :(得分:4)

  1. 不,你不能从方法中返回不同类型的对象(除非它们有一个共同的超类,在这种情况下这是可能的)。

  2. 如果我是你,当堆栈为空时我会抛出自定义Exception

  3. 例如:

    public int pop() throws EmptyStackException {
     ...
    }
    

    注意:如果您不想使用Exception(s),则可以定义无效的返回值,例如-1

    public int pop() {
        ...
    
        return -1; /* did this just to avoid the error*/
    }
    

答案 1 :(得分:2)

我会抛出一个异常来指示堆栈是空的,但是,如果你不想这样做,你可以return 0并且它将成为调用者如果堆栈为空,则有责任产生错误或任何他想要的东西。

答案 2 :(得分:2)

您可以使用Integer作为返回类型,并在堆栈为空时返回null

感谢@LuiggiMendoza

答案 3 :(得分:0)

方法不可能有不同的返回类型。

你应该将你的功能分为两个单独的方法:1)检查列表是否为空,2)从列表中弹出。

public boolean hasContent () {
    //Check to see if there is something to pop()
}

public int pop() {
    //Pop off the stack
    //Throw an error or return some sort of default empty value if there is nothing to pop
}

...

//usage
if(stack.hasContent()) {
  stack.pop()
}