|
1 | 1 | /** |
2 | 2 | * Fruit exercise. |
3 | 3 | */ |
4 | | -public class Fruit { |
5 | 4 |
|
| 5 | +/* |
| 6 | +The purpose of this exercise is to practice reading code and recognizing the traversal |
| 7 | +patterns in this chapter. The following methods are hard to read, because instead of using |
| 8 | +meaningful names for the variables and methods, they use names of fruit. |
| 9 | +For each method, write one sentence that describes what the method does, without getting |
| 10 | + into the details of how it works. For each variable, identify the role it plays. |
| 11 | + */ |
| 12 | +public class Fruit { |
| 13 | +//Int method defining an int array named "a". one param |
6 | 14 | public static int banana(int[] a) { |
7 | 15 | int kiwi = 1; |
8 | 16 | int i = 0; |
| 17 | + //While 'i' is less than the array length |
9 | 18 | while (i < a.length) { |
10 | | - kiwi = kiwi * a[i]; |
11 | | - i++; |
| 19 | + kiwi = kiwi * a[i]; //array counting by 1 |
| 20 | + i++;// allows i to traverse through the index by 1 |
12 | 21 | } |
13 | | - return kiwi; |
| 22 | + return kiwi; // ==3 |
14 | 23 | } |
15 | | - |
| 24 | + //Two params. Int method defining an int array named "a". param for an int variable # of grapes |
16 | 25 | public static int grapefruit(int[] a, int grape) { |
17 | | - for (int i = 0; i < a.length; i++) { |
18 | | - if (a[i] == grape) { |
19 | | - return i; |
| 26 | + for (int i = 0; i < a.length; i++) { // As long as 'i' is below the array length run the code below. |
| 27 | + if (a[i] == grape) { // When the index i is equal to grape |
| 28 | + return i; //return i's index |
20 | 29 | } |
21 | 30 | } |
22 | | - return -1; |
| 31 | + return -1; // return once the loop is complete |
23 | 32 | } |
24 | | - |
| 33 | + // Two params. Int method defining an int array named "a". param for an int variable # of apple |
25 | 34 | public static int pineapple(int[] a, int apple) { |
26 | 35 | int pear = 0; |
27 | | - for (int pine: a) { |
| 36 | + for (int pine: a) { //for each pine value in the a[] run this loop |
28 | 37 | if (pine == apple) { |
29 | | - pear++; |
| 38 | + pear++; //pear adds one every time the if statement is true |
30 | 39 | } |
31 | 40 | } |
32 | | - return pear; |
| 41 | + return pear; //return the new value after the loop is done |
33 | 42 | } |
34 | 43 |
|
35 | 44 | } |
0 commit comments