弹出从 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: 请不要在回答之前继续我的代表,我是 Noob in java
/p>
最佳答案
不,您不能从方法返回不同类型的对象(除非它们有一个共同的父类(super class),在这种情况下这是可能的)。
如果我是你,我会在堆栈为空时抛出一个自定义的
Exception
:
例如:
public int pop() throws EmptyStackException {
...
}
注意:如果您不想使用Exception
(s),您可以定义一个无效的返回值,例如-1
。
public int pop() {
...
return -1; /* did this just to avoid the error*/
}
关于java - 根据条件从方法返回 boolean 值或整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21556621/