I am a beginner in java and am writing a stack class using array.
So I have a method in this class called pop
public int Pop(){
if (current_size >0)
{ // do something
return ele;
}
// return nothing <-- ths is where error is
}
Since i have the return type int.. the class is always expecting to return something. How should I tackle such cases where the method wil return something if the condition is true else it wont shouldnt return anything? Thanks
-
There's....a lot wrong here. First, where is your array? You're not using it in this method. Second, it's difficult to decide what to return when the stack is empty, since any primitive int may be a valid entry in the stack. Third, I don't see anything that reduces the size of the stack or adjusts where the end of the stack is pointing to.Makoto– Makoto2012年09月24日 02:40:59 +00:00Commented Sep 24, 2012 at 2:40
5 Answers 5
You must always return something (unless your method is void) or throw an exception. You could try this:
public int pop() {
if (current_size > 0)
return ele;
throw new EmptyStackException();
}
Comments
Without knowing what your desired behavior is, it is hard to tell you, but I can provide a couple suggestions.
- If you want to truly return nothing, you should change the return type to be the
Integerwrapper class rather than theintprimitive. This way you can returnnullwhich would be nothing. If this is an exceptional case, perhaps you want to
throwanException.if (evaluateSomething()) { // do something in response... } else { throw new RuntimeException("You can't do that!"); }
Comments
You could raise an exception when the stack is empty, or you could return a special int like -1 if your stack never has negative numbers.
throw new StackIsEmptyException();
Comments
You need to have a return statement or throw an exception for all possible exit point.
Comments
Unless your method is void, you must either return a variable or throw/catch an exception. Something like this should do;
public int pop()
{
if (current_size > 0)
return ele; //return variable
throw new EmptyStackException(); //throw new exception
}