Savitch 7.1-7.5
1
2
3
4
5
6
7
8
9
// the declaration and initialization can be on a single line
double[] temperature; // declares variable
temperature = new double[7]; // initializes to new array object
// Assign 68 to indexed variable temperature[3]
temperature[3] = 68;
// Access the value of temperature[3] in an expression
double celsiusTemp = (temperature[3] - 32) * 5 / 9;
for
Loops
1
2
3
4
5
6
7
8
System.out.println("Enter 7 temperatures:");
for (int index = 0; index < 7; index++)
temperature[index] = keyboard.nextDouble();
System.out.println("The 7 temperatures are:");
for (int index = 0; index < 7; index++)
System.out.print(temperature[index] + " ");
System.out.println();
1
Base_Type[] Array_Name = new Base_Type[Length];
1
Array_Name[Index]
length
length
.
1
2
Species entry = new Species[20];
System.out.println(entry.length); // displays 20
length
instance variable is final, so its value cannot be changed.
1
entry.length = 10; // Illegal!
length
instance variables in its loop condition:
1
2
for (int index = 0; index < temperature.length; index++)
temperature[index] = keyboard.nextDouble();
for-each
Loopsfor-each
loop can be used to iterate though the items in array.
1
2
3
4
5
6
7
8
9
10
11
// value is initially assigned temperature[0], then is assigned
// the next item in the array before each successive iteration
for (int value : temperature)
{
if (value < average)
System.out.println(value + " below average.");
else if (value > average)
System.out.println(value + " above average.");
else // value == average
System.out.println(value + " the average.");
}
1
2
3
4
5
6
7
8
int index = 0;
int number = keyboard.nextInt();
while ((index < list.length) && (number >= 0))
{
list[index] = number; // index is guaranteed to be in bounds
index++;
number = keyboard.nextInt();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
// Option 1: adjust index when displaying it to the user
int [] hours = new int[NUMBER_OF_EMPLOYEES];
for (int index = 0; index < hours.length; index++) {
System.out.println("Enter hours for employee " + (index + 1));
hours[index] = keyboard.nextInt();
}
// Option 2: allocate an extra item and skip item at index 0
int [] hours = new int[NUMBER_OF_EMPLOYEES + 1];
for (int index = 1; index < hours.length; index++) {
System.outprintln("Enter hours for employee " + index);
hours[index] = keyboard.nextInt();
}
1
double[] reading = {3.3, 15.8, 9.7}
0
for int
s).
1
2
3
int [count] = new int[100];
for (int index = 0; index < 100; index++)
count[index] = 0;
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Section
{
private Course course;
private int sectionSize;
private Student[] roster;
public Section(Course course, int sectionSize)
{
this.course = course;
this.sectionSize = sectionSize;
this.roster = new Student[sectionSize]; // does not create the
} // Student objects
}
int
can be passed as an argument to a method with a parameter of type int
.
1
2
3
4
5
6
7
8
9
10
public static double getAverage(int num1, int num2)
{
return (num1 + num2 ) / 2.0;
}
public static void main(String[] args)
{
int[] score = {72, 81};
double average = getAverage(score[0], score[1]);
}
1
2
3
4
5
6
7
8
9
10
11
12
public static void incrementArrayBy2(double[] arr)
{
for (int index = 0; index < arr.length; index++)
arr[index] = arr[index] + 2;
}
public static void main(String[] args)
{
double[] number = {5, 2, 7, 4, 9, 0};
incrementArrayBy2(number);
// number is now {7, 4, 9, 6, 11, 2}
}
main
1
public static void main(String[] args)
args
is initialized to the command line arguments used when the program is launched.
1
java TestProgram Sally Smith
args[0]
would be "Sally"
and args[1]
would be "Smith"
.=
and ==
operators behave in the same way they do with other objects.
1
2
3
4
5
6
7
8
9
10
11
12
int[] first = {8, 3, 1, 9, 2};
int[] second = {8, 3, 1, 9, 2};
// first and second reference different objects so first != second
first[2] = 5;
// second[2] still has a value of 1
second = first;
// first and second reference the same object so first == second
first[2] = 7;
// second[2] also has a value of 7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static int[] getSquares(int size)
{
if (value <= 0)
{
System.out.println("Error: can not create array of size " + size);
System.exit(0);
}
int[] squares = new int[size];
for(int index = 0; index < size; index++)
squares[index] = index * index;
return squares;
}
// example method call: int[] squareArr = getSquares(10);
SimpleList
that keeps track of a list of items.SimpleList(int maxItems)
void addItem(String item)
String getItemAt(int position)
boolean contains(String item)
int getNumItems()
START_POSITION
that is et to the initial position of 1.SimpleList
class
1
2
3
4
5
6
7
8
9
10
11
12
SimpleList shoppingList = new SimpleList(5);
shoppingList.addItem("A loaf of bread");
shoppingList.addItem("A stick of butter");
shoppingList.addItem("A container of milk");
int position = shoppingList.START_POSITION;
while(position <= shoppingList.getNumItems()) {
String next = shoppingList.getItemAt(position);
System.out.println(next);
position++;
}
SimpleList
class
1
2
3
4
5
6
7
8
9
10
11
12
/** A list of items */
public class SimpleList {
public static final int START_POSITION = 1;
private int numItems; // may be < items.length
private String[] items;
/** Create an empty list with a given capacity */
public SimpleList(int maxItems) {
items = new String[maxItems];
numItems = 0;
}
addItem
Method
1
2
3
4
5
6
7
8
9
10
11
12
/** Add an item to the list */
public void addItem(String item) {
if (!contains(item)) {
if (numItems == items.length) { // array is full
System.out.println("Adding item to full list!");
System.exit();
}
else {
items[numItems] = item;
numItems++;
}
}
getItemAt
Method
1
2
3
4
5
6
7
8
9
10
11
12
/** Get the item at the given position */
public String getItemAt(int position) {
String result = null;
if ((1 <= position) && (position <= numItems))
result = items[position – 1];
return result;
}
/** Get the number of items in the list */
public int getNumItems() {
return numItems;
}
SimpleList
class uses a partially filled array to store its items.numItems
instance variable.0
though numItems - 1
.0
, first
and last
indexes can used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static void selectionSort(int[] anArray) {
for (int first = 0; first < anArray.length - 1; first++) {
int smallest = getIndexOfSmallest(first, anArray);
swap(first, smallest, anArray);
}
}
private static void swap(int i, int j, int[] arr) {
int temp = arr[i]; // save the value at index i
arr[i] = arr[j]; // copy the item at index j to index i
arr[j] = temp; // copy saved value to index j
}
private static int getIndexOfSmallest(int start, int[] arr)
{
// assume the smallest item is at the start index
int min = start;
// look for something smaller
for (int curr = start + 1; curr < arr.length; curr++)
if (arr[curr] < arr[min])
min = curr; // found something smaller
// return the index of the smallest item found
return min;
}
java.util
package contains a class called Arrays
that has more efficient method called sort
.
1
2
3
4
5
// sort an entire array
Arrays.sort(anArray);
// sort a range of an array from first to last
Arrays.sort(anArray, first, last);
Comparable
interface.
1
2
3
4
5
6
7
8
public boolean contains(String item) {
boolean found = false;
int index = 0;
while(!found && (index < numItems))
if(item.equalsIgnoreCase(items[i])) found = true;
else index++;
return found
}
1
Array_Name[Row_Index][Column_Index]
table
would be table[3][2]
.
1
2
3
4
int[][] table; // declares a 2D array variable
table = new int[10][6]; // allocates a 2D array
int[][] table = new int[10][6]; // same as 2 lines above
1
2
3
for (int row = 0; row < 10; row++) // iterates through rows
for (int col = 0; col < 6; col++) // iterates through columns
table[row][col] = row * 6 + col; // initializes elements
1
2
3
4
5
6
7
8
9
10
11
12
public static double[][] copy(double[][] startArray, int size)
{
double[][] temp = new double[size][size];
for (int row = 0; row < size; row++)
for (int col = 0; col < size; col++)
temp[row][col] = startArray[row][col];
return temp;
}
// method call:
double[][] arr1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
double[][] arr2 = copy(arr1, 3);
1
int[][] table = new int[10][6];
table
refers to an array of 10 arrays, and table.length
is 10.table[0]
refers to an array of 6 int
s, and table[0].length
is 6.
1
2
3
for (int row = 0; row < table.length; row++)
for(int col = 0; col < table[row].length; col++)
table[row][col] = row * table[row].length + col;
1
2
3
4
int[][] ragged = new int[3][]; // allocate an array with 3 rows
ragged[0] = new int[5]; // first row has 5 entries
ragged[1] = new int[7]; // second row has 7 entries
ragged[2] = new int[4]; // third row has 4 entries
1
2
3
4
5
for (int row = 0; row < ragged.length; row++) {
for (int col = 0; col < ragged[row].length; col++)
System.out.print(ragged[row][col] + " ");
System.out.println();
}
new
, although the syntax is slightly different from that used when creating objects of a class.a[i]
is an indexed variable of the array. The index i
must have a value greater than or equal to 0 and strictly less than a.length
, the array’s length. If i
has any other value when you run your program, an array index out-of-bounds error will occur, causing an error message.int
variable to the number of these values. In this case, you have a partially filled array.