Lecture 14, CS 302-6, October 5
i. Think of scanner as processing a line of inputs
ii. hasNextInt looks at which one is coming up next
iii. .nextInt, .next, etc actually take that one out of line and process it.
i. Declare/initialize
1. int[] numbers=new int[3];
2. int[] numbers; numbers=new int[3];
3. int[] numbers={1,2,3};
ii. How to use
1. numbers[1] (‘numbers sub 1’) -> 2
2. numbers[0] -> 1
iii. Characteristics
1. Type – int, double, String, etc
2. Length
a. numbers.length
i. For(int value:data)
ii. Example – TestScores.java
1. Cannot be changed after you have initialized it
2. Can change after declaring, though.
Eg int[] numbers; //do stuff; numbers=new int[var];
1. run-time, not compile time, so be careful!
ii. The exception will tell us why/where it failed, which is good for tracking down errors
i. Note –these require traversing the entire array
i. Start at beginning, search until we find data
ii. Note – search can abort early, once we find answer
i. Faster than linear
ii. Start in middle. If our value is greater, check second half. If our value is less, check first half. Repeat with that section until we find the number or run out of elements.
iii. Only works if the array is sorted beforehand
iv. Real-world example – searching through a dictionary.
1. Start in middle, then half each way, etc.
i. Removal - Start at the index you want to remove +1. Copy that into the index you want to remove. Then, move up one and repeat.
ii. Insertion – start at end of the array. Copy the value into the fist empty slot. Then, move back one step, and repeat. When you’ve reached the correct position, insert new item.
i. For loop – for each element in the old array, store it in the corresponding index in the new array.
ii. Easier - Int[] numbers2=Arrays.copyOf(numbers, numbers.length)
i. Find the smallest value in an array, switch it with the first value. Then, starting at the second value, find the smallest and switch it with the second value. Repeat.
ii. Example – SelectionSort.java
i. More about this in data structures, algorithms
ii. Arrays.sort – method to efficiently sort arrays