Arrays


Primitive and Object Arrays

ArrayExamples.java
(uses Bunny.java)

ManyNames.java
ManyNamesHarness.java

Deitel 7


Classwork

Do the following in your main class. I suggest you do these before returning to the previous classwork if you were having trouble. When you make methods in the class with main, add the keyword static, just as main uses it.

☑ Write a method doubleIt which takes an array of ints and returns a new array where each element is twice the value of the corresponding int in the original array. It does not make changes to the original array.

☑ Write a method findHighIndex which takes an array of ints and returns a single int which is the index where the highest value in the array is found. So if it were given {99, 22, 109, 3} it would return 2 since the highest value is at index 2.

☑ In the main, create an array of ints with at least 5 elements using special initialization. Create another variable and set it equal to the result of calling doubleIt on the array you just created. Then print the elements of both arrays side by side using a single for loop. Then use findHighIndex on the original array, and use the value returned to print the corresponding value in the doubled array.


☑ Write a method randomWord which takes an array of Strings and returns a randomly chosen String from the array (hint: you can randomly choose an index in the array and then return the string at that index). Test this in main


[EC] Add a method showOrNo which takes an array of Bunnys and an array of booleans. Print each element of the array of Bunnys but only if the boolean at the same index in the boolean array is true. Test it in main.

[EC] Write a method findHighLowIndex which takes an array of ints and returns an array containing the indices of the highest and lowest values in the array. So if it were given {99, 22, 109, 3} it would return {2, 3} since the highest value is at index 2 and the lowest is at index 3.

[EC] In BunnyFarmer add a private method findHighBunIndex which returns the index of the Bunny in the hutch with the highest carrotCount. Add a private method randomBun that returns the index of a randomly chosen Bunny in the hutch. (hint: there may be empty spaces in the hutch, we should never be using those indices) Add a public method pickDinner which, as long as the hutch is not empty, looks at the Bunny with the highest carrotcount. If it has carrotCount higher than 5, report that it has been eaten, but if not, complain that they are all too skinny and choose another random bunny, and report that one is being eaten.