Reputation: 33243
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
Upvotes: 1
Views: 111
Reputation: 376
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
}
Upvotes: 1
Reputation: 41097
You need to have a return statement or throw an exception for all possible exit point.
Upvotes: 1
Reputation: 21
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();
Upvotes: 2
Reputation: 129507
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();
}
Upvotes: 7
Reputation: 42849
Without knowing what your desired behavior is, it is hard to tell you, but I can provide a couple suggestions.
Integer
wrapper class rather than the int
primitive. This way you can return null
which would be nothing.If this is an exceptional case, perhaps you want to throw
an Exception
.
if (evaluateSomething()) {
// do something in response...
} else {
throw new RuntimeException("You can't do that!");
}
Upvotes: 3