Unit 6 Collegboard Arrays
arrays -array: type of data structure -array and arrayLists are different -ex of declaration: int [] array = new int [10];
- other ways:
- final int length = 10, int[] numbers = new int
- int length = in.nextInt();, double[] data = new double[length]
- int[squares]= {0,1,2,3,4}
-common errors:
- bound error: trying to access a variable that doesnt exist -uninitialized and unfiled arrays -traverse an array: use any sort of loop but for loops are easiest to access
- int i=0; i<array.length; i++
- enhanced for loops -- can use basic for loop to visit all elements in an array
public class Array
{
private static int [] values = {1,2,3,4,5};
public void printValues(){
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
}
public void swapFirstAndLast()
{
int lastElement = values[values.length-1];
values[values.length-1] = values[0];
values[0] = lastElement;
}
public void allZero()
{
for(int i=0; i < values.length; i++){
values[i] = 0;
}
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void main(String[] args){
System.out.println("Swapping elements:");
Array swapFirstAndLast = new Array();
swapFirstAndLast.swapFirstAndLast();
swapFirstAndLast.printValues();
System.out.println("Replacing elements with zero:");
Array allZero = new Array();
allZero.allZero();
allZero.printValues();
System.out.println("are the orginal values sorted in increasing order?");
System.out.println(isSorted(values));
}
}
Array.main(null);