Activity 2.5 - Using arrays
Topic
This activity is about array access.
Materials
In addition to the discussion of the solution in the Solution document, the
project for this activity contains two classes:
- Ex2_5, for which you need to supply additional code;
- Main, which is run to test the code.
Tasks
It
is common to list the planets of the Solar System in order of their distance
from the Sun. However, many people have trouble remembering how the order goes.
The method selectAPlanet was supposed to help with this, but unfortunately the programmer left
out some segments of code:
- The check that
the user submits a sensible planet number is incomplete;
- The code to
print a planet's name was omitted;
- Pluto was omitted from the list of planets. (Pluto isn't considered to be a planet.)
The existing method runs but does not produce correct output. Your job is to
supply the missing code.
Instructions
- Run the project. You should find it prompts
for a planet number. At this point you need to type a number in the window
at the bottom of the NetBeans window and press Enter. The code
should then print a planet name, but does not.
- Open
the class Ex2_5 and type in code missing from the method selectAPlanet at the two places indicated by comments. Don't
forget that in Java the index of an array starts at 0, not 1. Re-run the project to check planet names are correctly printed.
- Now
modify the method to add "Pluto" to the array planets. If you have made the other changes in the right
way, the program should still run properly, without further modification.
Confirm this by executing the revised version.
Notes
This project makes use of
the utility class Scanner to perform keyboard input. This class
is discussed in Unit 4.