Help with these two codes
I want to write a code to judge if an int[3] array is full then throws a stackfullexception to tell user the stack is full, if the user wants to put new data in the array.
When I try two different ways to write,one is :
Code:
public void push(int i) throws StackFullException {
top++;
if(top >= 3)
throw new StackFullException("The stack is full.");
stack[top] = i;
System.out.println(stack[top]);
}//close push()
this works ok, when I call push(i) four times in the main() the output is:
3
5
6
The stack is full.
but if I change the code to: Code:
public void push(int i) throws StackFullException {
if(top++ >= 3)
throw new StackFullException("The stack is full.");
stack[top] = i;
System.out.println(stack[top]);
}//close push()
the output is:
3
5
6
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at com.black.exception.Stack.push(Stack.java:10)
at com.black.exception.StackMain.main(StackMain.java: 10)
Why I just put top++ in the if, the runtime exception happens?I still can't figure out why.
Please if you can help to explain.
Hope you can understand my poor English, Thank you, best regards.
Re: Help with these two codes
I just figure out why.
Because if(top++ >= 3) means it will decide if top >= 3 or not ,then top + 1.Because top is still 2, so it won't throw an exception.
But after that , top will plus one , and run the stack[top] = i;
And it will run stack[3] = 1 , that's why ArrayIndexOutOfBoundException happen.
Re: Help with these two codes
In Java, array indexes are zero based. A 3 element array has elements at [0] [1] and [2].
db
edit Glad you found that out for yourself.
Re: Help with these two codes
Quote:
Originally Posted by
DarrylBurke
In Java, array indexes are zero based. A 3 element array has elements at [0] [1] and [2].
db
edit Glad you found that out for yourself.
Thank you for reminding me that.
Sometimes I am still confused with some basic syntaxes like differents between x++ and ++x etc.
Hope one day I can write codes as breathing air naturally.
Re: Help with these two codes
Oh, and for your future reference: Forum Rules -- particularly the third paragraph
db
Re: Help with these two codes
Quote:
Originally Posted by
DarrylBurke
Oh, and for your future reference:
Forum Rules -- particularly the third paragraph
db
OH.....I am Really Sorry about that......didn't notice that before.......Apologies:(sweat):
Thanks again.
I will be more careful about posting threads in the future.
Best Regards.