Unit 6 Array
Homework for Unit 6: Array
Notes
Arrays store one data type and has a fixed size.
The syntax to create an array is: data type[] name = new data type[num]
. This creates an array with constructors.
The other way to create an array is to pre-initialize it. To do this, type data type[] name = {elements}
.
The element of arrays can be accessed through the index.
Errors
ArrayIndexOutOfBoundsException
: Arrays can be iterated through loops. If the loop accesses an index that the array does not have, this error can occur. An example is listed below:
int[] numbers = {1, 2, 3};
for (int i = 0; i <= numbers.length; i++) { // uh-oh
System.out.println(numbers[i]);
}
In the example above, the code failed because the for loop iterates from i = 0 to i = 3. The array does not contain an element at index 3. Therefore, the code needs to be altered below:
int[] numbers = {1, 2, 3};
for (int i = 0; i < numbers.length; i++) { // uh-oh
System.out.println(numbers[i]);
}
int[] numbers = {1, 2, 3};
int sum = 0;
for (int num : numbers) { // uh-oh
sum += num;
}
System.out.println(sum);
public void addMembers(String[] names, int gradYear) {
for (int i = 0; i < names.length; i++) {
memberInfo member = new MemberInfo(names[i], gradYear, true);
memberList.add(member);
}
}
Comments:
My solution matched up with the official solutions. Something that I could have used though, would be the for each loop to iterate through each element in the array.
public void addMembers(String[] names, int gradYear) {
for (String n : names) {
memberInfo member = new MemberInfo(n, gradYear, true);
memberList.add(member);
}
}
int[] arrayOne = {1, 3, 5, 7, 9};
for (int i = 0; i < arrayOne.length(); i+=2) {
System.out.println(arrayOne[i]);
}