CP2003 - Tutorial Three: The Wrath of Java
Again, the end of this tutorial can spill over into next week if necessary.
- If you haven't already done so (as part of the second last question
from last week) write a program that creates and initialises an integer
array of size 10. The program should then take two command-line arguments
and interpret these as integers (hint: use Integer.parseInt(...)) which
serve as array indices. The program should then print out the corresponding
two array elements.
The second part of this problem is to test for exceptions. Your program
should test (at least) for a specific exception (possibly
NumberFormatException) arising because the parameters were not integers
and for an exception thrown due to the parameters being outside the bounds of
the array. Note, you can cascade the catch statements to be more efficient.
- Amend your program to take the input values via standard input (that
is, prompt the user and read-in their input) instead of the command line.
- Amend this program to also initialise your array via standard input,
reading in the entire array in one line. That is, something like this:
Enter the array contents:
21 32 5 1 2 13 23 11 22 6
You should then continue your program execution as normal. A big hint on
how to do this efficiently is to use StringTokenizer (look it
up in the Java
Application Interface). You can assume that the user will enter exactly
10 values (which may or may not be integers).
- Again, amend your array index code - this time to use a Vector instead of
an array. It should now be able to handle and store any number of values.
Copyright © 2000. James Cook University. All rights reserved.