Results 1 to 6 of 6
Thread: Help with these two codes
- 06-09-2012, 03:04 AM #1
Member
- Join Date
- Apr 2012
- Posts
- 16
- Rep Power
- 0
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 :
this works ok, when I call push(i) four times in the main() the output is:Java 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()
3
5
6
The stack is full.
but if I change the code to:the output is:Java 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()
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.
- 06-09-2012, 05:55 AM #2
Member
- Join Date
- Apr 2012
- Posts
- 16
- Rep Power
- 0
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.
- 06-09-2012, 05:57 AM #3
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.Why do they call it rush hour when nothing moves? - Robin Williams
- 06-09-2012, 06:37 AM #4
Member
- Join Date
- Apr 2012
- Posts
- 16
- Rep Power
- 0
- 06-09-2012, 08:11 AM #5
Re: Help with these two codes
Oh, and for your future reference: Forum Rules -- particularly the third paragraph
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 06-09-2012, 12:03 PM #6
Member
- Join Date
- Apr 2012
- Posts
- 16
- Rep Power
- 0
Similar Threads
-
Need help with my codes
By vesperia in forum NetBeansReplies: 3Last Post: 06-29-2011, 12:23 PM -
I need some codes
By johnmergene in forum New To JavaReplies: 11Last Post: 01-25-2011, 03:42 AM -
What do the following codes do?
By javaguy2 in forum New To JavaReplies: 2Last Post: 01-23-2011, 10:23 PM -
two short codes
By Libertyman in forum New To JavaReplies: 7Last Post: 06-21-2010, 03:22 PM -
What's wrong with my codes?
By ayoood in forum New To JavaReplies: 16Last Post: 09-01-2008, 03:57 AM


2Likes
LinkBack URL
About LinkBacks
Reply With Quote
.gif)

Bookmarks