Arrays
Goals
- Learn about Java arrays. An array is a data structure that can contain many items with the same data type.
- Practice coding common array-processing patterns (sum, min, max).
- Learn how to create a method that takes an array as an argument.
- Learn how to write a method that returns an array.
- Be aware of the fact that when an array is passed to a method, a reference is passed, which means that the method can change the array.
Setting up and accessing a fixed-length array (File: Five.java)
Download the file Five.java which contains "skeleton code." This is a valid Java program, but it doesn't yet do what we want it to.
Complete Five.java by doing the following:
- Make the existing constructor work
- Add a new constructor that accepts five integer arguments and places those arguments in the data array
- Make the fillArray, sumArray and report methods work as described in the comments above them.
- Add a getData method that takes no arguments and returns the instance variable that is an array of five integers. Why might it be a bad idea to have such a method?
Sample Interactions five.hist
> Five test = new Five();
> test.sumArray() 0
> test.report()
0
0
0
0
0
sum: 0
> test.fillArray(0);
> test.sumArray()
100
> test.report()
0
10
20
30
40
sum: 100