Unit 6 - Arrays
dataType[] arrayName = new dataType[numberOfItems];
int[] arraySample = {1,3,5,7,9};
int[] arrayOne = {1, 3, 5, 7, 9};
for(int i = 0; i < arrayOne.length; i++) {
System.out.println(arrayOne[i]);
}
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};
for (int i = 0; i < myFruits.length; i++) {
System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};
for (int i = 0; i < myFruits.length+1; i++) {
System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
class Main {
static int length;
public static void printArray(int[] array)
{
for (int i = 0; i < length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void sortArray(int[] array)
{
int temporary = 0;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (array[i] > array[j]) {
temporary = array[i];
array[i] = array[j];
array[j] = temporary;
}
}
}
System.out.println(
"Elements of array sorted in ascending order: ");
printArray(array);
}
public static void main(String[] args)
{
int[] array = new int[] { -5, -9, 8, 12, 1, 3 };
length = array.length;
sortArray(array);
}
}
Main.main(null);
for (dataType i: arrayName) {
System.out.print("hi");
}
- use array.length to find number of elements in an array
- to find a specific element, do arrayname[element number]
ie: finding sum
int[] array = {3, 2, 4, 17};
int sum = 0;
for (int number: array) {
sum += number;
}
System.out.println(sum);
public void addMembers(String[] names, int gradYear)
{
for(String name : names)
memberList.add(new MemberInfo(name, gradYear, true));
}