Very simple. Just what we had in our functions, but now in it's own function, so we can replace everything with last()
The next part is harder, though. We need to deal with Exceptions, try and catch. I don't want to go into detail with that stuff right now, so I'll provide only a short explanation after you see the code:
From what I understand (Correct me if I'm wrong), there's a couple of things you can do when encountering an error,. First is to "catch" is, which we see in the pop method. With the exception caught ("Exception e" is just generic, any old thing), we can then perform whatever task. In this case, since the method is void type, just print out an error message with System.err.println().
If you were to try and catch the error with a non-void method, you should probably be aware that it still expects you to return an int or String or whatever, so you should specify in comments what number (normally -1) represents a failure, then move on with it.
The second method is to "throw" your exception. In top(), I did the whole try-catch thing again, but its not needed. Throwing an error actually tells the program, hey, something went wrong here, stop doing things! No more of the program is run.
Of course, you could have just used if-statements, along with isEmpty(), but you'd still have to return an int in the case of top(), so maybe have 1 out-of-bounds number would be prudent. -1 works well in a few cases. Another function entirely might be needed to run top if and only if isEmpty() is false, being another helper function. Really, it depends on your needs and wants and expectations of the program.
That's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!
And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us.
programming is like a foreign language for me
ReplyDelete@Max
ReplyDeleteYeah, it's...tough to get a grasp on for a lot of people, including myself.
This is kind of important. I'd better read it over a few more times until I get it completely.
ReplyDelete