chapter 8 arrays
DESCRIPTION
Chapter 8 Arrays. One-dimensional Arrays Two-dimensional Arrays Computer Graphics. One-dimensional Arrays. So far, most of our programs input few values Program stores these values in a few variables Program does some calculation, then displays output. Program. Variable 1. Value 1. - PowerPoint PPT PresentationTRANSCRIPT
Programming and Problem SolvingWith Java
Copyright 1999, James M. Slack
Chapter 8ArraysOne-dimensional ArraysTwo-dimensional ArraysComputer Graphics
Programming and Problem Solving With Java 2
One-dimensional ArraysSo far, most of our programs input few values
Program stores these values in a few variablesProgram does some calculation, then displays output
Value 1
Value 2
Value 3
Output
Program
Variable 1
Variable 2
Variable 3
Programming and Problem Solving With Java 3
One-dimensional ArraysProgram may read lots of values
But reads and processes one at a time
Value 1
Value 2
Value 3
Output
Program
Variable 1Value 4
Value 5
Value n
...
Programming and Problem Solving With Java 4
One-dimensional ArraysSome programs need to store many values
Example: read many values, display in reverse orderTedious to create a variable for each value
Value 1
Value 2
Value 3
Output
Program
Value 4
Value 5
Value n
...
Variable 1
Variable 2
Variable 3
Variable 4
Variable 5
Variable n
...
Programming and Problem Solving With Java 5
One-dimensional ArraysAlternative: use an array
Define one array variableStore many values in that single variableAccess the values in any order in the array
Value 1
Value 2
Value 3
Output
Program
Array variableValue 4
Value 5
Value n
...
Programming and Problem Solving With Java 6
One-dimensional ArraysDifference between simple and array variables
Simple variable holds a single value
Array variable holds several values
intNum(integer variable)
437
intNum[0]
437
intNum[1]
12
intNum[2]
94
Programming and Problem Solving With Java 7
Arrays: DefiningTo define an array variable
int[] intNum;
Must then create an array objectintNum = new int[3];
Creates an array object with 3 integers
Can do in one stepint[] intNum = new int[3];
intNum[0]
0
intNum[1]
0
intNum[2]
0
Programming and Problem Solving With Java 8
Arrays: DefiningAfter defining the array, access elements by
subscriptint[] intNum = new int[3];
intNum[0] = 437;intNum[2] = intNum[0] - 343;intNum[1] = (intNum[2] - 10) / 7;
intNum[0]
437
intNum[1]
12
intNum[2]
94
Programming and Problem Solving With Java 9
Arrays: DefiningExample program
import Keyboard;
public class ThreeIntegers{ static final int MAX_NUMBERS = 3;
public static void main(String[] args) throws java.io.IOException { // Define the array variable and allocate space for an // array object int[] intNum = new int[MAX_NUMBERS];
// Read in three numbers intNum[0] = Keyboard.readInt("First number: "); intNum[1] = Keyboard.readInt("Second number: "); intNum[2] = Keyboard.readInt("Third number: ");
// Display the array System.out.println(); System.out.println("The numbers are:"); for (int i = 0; i < intNum.length; i++) { System.out.println(intNum[i]); } }}
First number: 425Second number: 39Third number: -125
The numbers are:42539-125
intNum.length is size of array
Programming and Problem Solving With Java 10
Arrays: DefiningExample: Store rainfall data
Array must store 18 floating-point valuesdouble[] rainFall = new double[18];
Better approach -- use a constantstatic final int NUM_YEARS = 18;...double[] rainFall = new double[NUM_YEARS];
Can now assign values to positions in arrayrainFall[0] = 30.55;rainFall[1] = 23.94;rainFall[2] = 18.32;...
Year Rainfall Year Rainfall Year Rainfall
1982 30.55 1988 25.67 1994 28.76
1983 23.94 1989 29.45 1995 27.47
1984 18.32 1990 31.14 1996 25.43
1985 32.28 1991 23.52 1997 26.64
1986 27.87 1992 32.29 1998 29.37
1987 26.58 1993 21.23 1999 28.56
Programming and Problem Solving With Java 11
Arrays: DefiningArray of String objects
Define arraystatic final int NUM_NAMES = 5;
String[] name = new String[NUM_NAMES];
Assign valuesname[0] = "Smith";name[1] = "Jones";name[2] = "Miller";name[3] = "Lui";name[4] = "Gonzales";
Display valuesfor (int nameNumber = 0; nameNumber < name.length; nameNumber++){ System.out.println(nameNumber + ": " + name[nameNumber]);}
Output0: Smith1: Jones2: Miller3: Lui4: Gonzales
Programming and Problem Solving With Java 12
Arrays: DefiningArray of Money objects
Define arrayMoney[] quarterlySales = new Money[4];
Assign valuesquarterlySales[0] = new Money(400, 00); // first quarterquarterlySales[1] = new Money(450, 00); // second quarterquarterlySales[2] = new Money(375, 00); // third quarterquarterlySales[3] = new Money(425, 00); // fourth quarter
Display valuesfor (int quarter = 0; quarter < 4; quarter++){ System.out.println("Sales for quarter " + (quarter + 1) + ": " + quarterlySales[quarter]);}
OutputSales for quarter 1: 400.00Sales for quarter 2: 450.00Sales for quarter 3: 375.00Sales for quarter 4: 425.00
Programming and Problem Solving With Java 13
Arrays: DefiningInitial value of numeric array is zeros
static final int NUM_YEARS = 18;...double[] rainFall = new double[NUM_YEARS];
for (int year = 0; year < rainFall.length; year++){ System.out.print(rainFall[year] + " ");}System.out.println();
Output0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Initial value of object array (String, Money, ...) is nullstatic final int NUM_NAMES = 5;
String[] name = new String[NUM_NAMES];
for (int nameNumber = 0; nameNumber < name.length; nameNumber++){ System.out.print(name[nameNumber] + " ");}System.out.println();
Outputnull null null null null
Programming and Problem Solving With Java 14
Arrays: UsingArray variable + subscript = single element
static final int NUM_YEARS = 18;...double[] rainFall = new double[NUM_YEARS];double amount;
amount = 123.45;rainFall[0] = 30.55;rainFall[1] = 23.94;...
Treat rainFall[0] just like any double variableUsage Simple Variable Subscripted Array Variable
Assignment amount = 10.6; rainFall[3] = 10.6;
Input amount = Keyboard.readDouble();
rainFall[3] = Keyboard.readDouble();
Display System.out.println(amount); System.out.println(rainFall[3]);
Expression x = amount / 2; x = rainFall[3] / 2;
Comparison if (amount > 5.0) ... if (rainFall[3] > 5.0) ...
Pass to method check(amount); check(rainFall[3]);
Programming and Problem Solving With Java 15
Arrays: UsingExample: Compute average rainfall for all 18 years
Set up the rainFall arraydouble[] rainFall = new double[18];
rainFall[0] = 30.55;rainFall[1] = 23.94;...
Sum all the amounts - first (long!) approachtotal = rainFall[0] + rainFall[1] + rainFall[2] + rainFall[3] + rainFall[4] + rainFall[5] + rainFall[6] + rainFall[7] + rainFall[8] + rainFall[9] + rainFall[10] + rainFall[11] + rainFall[12] + rainFall[13] + rainFall[14] + rainFall[15] + rainFall[16] + rainFall[17];
Sum all the amounts - second (better) approachdouble total = 0.0;for (int year = 0; year < rainFall.length; year++){ total = total + rainFall[year];}
Display the averageSystem.out.println("Average rainfall is " + (total / rainFall.length));
Programming and Problem Solving With Java 16
Arrays: UsingAccess outside the array
double[] rainFall = new double[18];
rainFall[19] = -5;
Run-time errorjava.lang.ArrayIndexOutOfBoundsException: 19 at Test.main(Test.java)
Make sure array access is within bounds
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ??
Programming and Problem Solving With Java 17
Arrays: UsingDisplaying values of array
Must display individual valuesfor (int year = 0; year < rainFall.length; year++){ System.out.println(rainFall[year]);}
Reading values into an arrayMust read individual values
for (int year = 0; year < rainFall.length; year++){ rainFall[year] = Keyboard.readDouble("Enter rainfall for year " + year + ": ");}
Programming and Problem Solving With Java 18
Arrays: InitializingCan initialize values of array in definition
double[] rainFall = {30.55, 23.94, 18.32, 32.28, 27.87, 26.58, 25.67, 29.45, 31.14, 23.52, 32.29, 21.23, 28.76, 27.47, 25.43, 26.64, 29.37, 28.56};
Don't need to specify array size, or use new operatorInitialize array of objects
StringsString[] name = {"Smith", "Jones", "Miller"};
Other objectsMoney quarterlySales[4] = { new Money(400, 00), // first quarter new Money(450, 00), // second quarter new Money(375, 00), // third quarter new Money(425, 00) }; // fourth quarter
Programming and Problem Solving With Java 19
Arrays: Copying with Assignment// Copies one array to another using the// assignment operator
public class TestArrayAssignment{ public static void main(String[] args) { // Make an array int[] originalArray = { 7, 4, 5, 2 };
// Define another int[] aCopy;
// Copy using assignment aCopy = originalArray;
// Change value in original array originalArray[0] = 999;
// Display values in both arrays System.out.println(originalArray[0] + " " + aCopy[0]); }}
999 999
originalArray
null
aCopy
7
4
5
2
originalArray aCopy
7
4
5
2
Afterassignment
Beforeassignment
Programming and Problem Solving With Java 20
Arrays: CopyingTwo ways to make a copy of an array
Use for statement to copy individual elements// Make an arrayint[] originalArray = { 7, 4, 5, 2 };
// Define anotherint[] aCopy = new int[originalArray.length];
// Copy individual elementsfor (int element = 0; element < originalArray.length; element++){ aCopy[element] = originalArray[element];}
Use System.arraycopy() method// Make an arrayint[] originalArray = { 7, 4, 5, 2 };
// Define anotherint[] aCopy = new int[originalArray.length];
// Copy using arrayCopy()System.arraycopy(originalArray, // Source array 0, // Source array position aCopy, // Target array 0, // Target array position originalArray.length); // Number of elements
COPYCOPY
Programming and Problem Solving With Java 21
Arrays: Copying with arraycopy()// Copies one array to another using // System.arraycopy() public class TestArrayCopy{ public static void main(String[] args) { // Make an array int[] originalArray = { 7, 4, 5, 2 };
// Declare another and allocate space int[] aCopy = new int[originalArray.length];
// Copy using arrayCopy() System.arraycopy(originalArray, 0, aCopy, 0, originalArray.length);
// Change value in original array originalArray[0] = 999;
// Display value in copy System.out.println(originalArray[0] + " " + aCopy[0]); }}
999 7
originalArray aCopy
7
4
5
2
originalArray aCopy
7
4
5
2
Afterarraycopy()
Beforearraycopy()
7
4
5
2
Programming and Problem Solving With Java 22
Arrays: ParametersCan pass an array to a method
Array is an object, so it works like other object parameters
If method changes value in the array, will also change actual parameter
Method can store values in array for caller// Reads rain fall data from user into rainFall array parameterstatic void readRainFall(double[] rainFall)throws java.io.IOException{ for (int year = 0; year < rainFall.length; year++) { rainFall[year] = Keyboard.readDouble("Enter rainfall for year " + year + ": "); }}
Programming and Problem Solving With Java 23
Arrays: ParametersMethod can return array object
Useful when method allocates the array object// Reads rain fall data from user into rainFall array and// returns the arraystatic double[] readRainFall()throws java.io.IOException{ // Find out how large to make the array int numYears = Keyboard.readInt( "How many years of rainfall data? ");
// Allocate the array double[] rainFall = new double[numYears];
// Read data from user for (int year = 0; year < rainFall.length; year++) { rainFall[year] = Keyboard.readDouble("Enter rainfall for year " + year + ": "); }
// Return the array return rainFall;}
Programming and Problem Solving With Java 24
Arrays: ParametersWhat's wrong with this?
// Reads rain fall data from user into rainFall WRONG!!// array parameter (allocates space)static void readRainFall(double[] rainFall)throws java.io.IOException{ // Find out how large to make the array int numYears = Keyboard.readInt( "How many years of rainfall data? ");
// Allocate the array rainFall = new double[numYears];
// Read data from user for (int year = 0; year < rainFall.length; year++) { rainFall[year] = Keyboard.readDouble("Enter rainfall for year " + year + ": "); }}
Programming and Problem Solving With Java 25
Example: 1-column SpreadsheetUse of the program
--- One-column SpreadSheet ---
(D)isplay (E)nter (Q)uit: ePosition: 3Data: 59.5
(D)isplay (E)nter (Q)uit: ePosition: 5Data: 18.0
(D)isplay (E)nter (Q)uit: d3 59.55 18.0Total 77.5
(D)isplay (E)nter (Q)uit: ePosition: 3Data: 18.6
(D)isplay (E)nter (Q)uit: d3 18.65 18.0Total 36.6
(D)isplay (E)nter (Q)uit: q
Programming and Problem Solving With Java 26
Example: 1-column SpreadsheetCode
// This program stores a column of numbers. We can change// any of the numbers, and total them up. Then we can change the// numbers some more. User commands are://// D Display all nonzero entries in the column and the total// E Enter a new value for one of the entries// Q Quit the program
import Keyboard;
public class SpreadSheet{ static final int NUM_ENTRIES = 20;
public static void main(String[] args) throws java.io.IOException { double[] column = new double[NUM_ENTRIES]; char selection;
System.out.println("--- One-column SpreadSheet ---"); System.out.println();
Programming and Problem Solving With Java 27
Example: 1-column SpreadsheetCode (continued)
do { selection = Keyboard.readChar( "(D)isplay (E)nter (Q)uit: ", "deq"); switch (Character.toLowerCase(selection)) { case 'd': // Display the spreadsheet with total double total = 0.0; for (int loc = 0; loc < column.length; loc++) { if (column[loc] != 0.0) { System.out.println(loc + "\t" + column[loc]); total = total + column[loc]; } } System.out.println("Total\t" + total); break; case 'e': // Let user enter a new value in the spreadsheet int entry = Keyboard.readInt("Position: ", 0, column.length - 1); column[entry] = Keyboard.readDouble("Data: "); break;
Programming and Problem Solving With Java 28
Example: 1-column SpreadsheetCode (continued)
case 'q': // Do nothing, but could confirm whether to quit break;
default: System.out.println("Switch statement error"); break; } System.out.println(); } while (selection != 'q'); }}
Programming and Problem Solving With Java 29
Example: Letter CountingProgram to
count letter frequency in a text file
Program asks for input and output files
Input file name: frogs.txtOutput file name: frogs.out
Letter Frequency a 15 b 5 c 3 d 7 e 25 f 7 g 7 h 12 i 12 j 0 k 1 l 7 m 5 n 11 o 19 p 1 q 1 r 16 s 12 t 15 u 5 v 2 w 6 x 0 y 3 z 0
Letter FrequencyProgram
Output File: frogs.out
FROGSFrogs are amphibians, and arefound all over the world. Somerequire water, while others areat home on land. Frogs eatinsects and other food byshooting out their long, stickytongue. They have webbed feetwhich are suitable for swimming.
Input File: frogs.txt
Programming and Problem Solving With Java 30
Example: Letter CountingUse array of 26 integers to store count of each letter
Problem: How to map letter (character) to position in array (integer)?Program reads letter 'B' in fileTranslate 'B' into 1 Increment array at position 1
0 1 2 3 4 23 24 25
Count
of A's
Count
of B's
Count
of C's
Count
of D's
Count
of E's
Count
of X's
Count
of Y's
Count
of Z's
...
Programming and Problem Solving With Java 31
Example: Letter CountingTwo ways to map letters to subscripts
Use switch statement (long, tedious, error-prone)switch (inputChar){ case 'A': index = 0; break; case 'B': index = 1; break; ...}
Use static method!// letterToInt: Returns 0 for 'A' or 'a', 1 for 'B'// or 'b', etc.static int letterToInt(char letter){ return ((int) Character.toLowerCase(letter)) - (int) 'a';}
'B' 'B' 1 1
Programming and Problem Solving With Java 32
Example: Letter CountingExample: 'B' 1
Convert to lower case 'b'Character.toLowerCase('B')
Convert to Unicode 98(int) 'b'
Subtract 'a'98 - (int) 'a'= 98 - 97
Result is 1
Code Char Code Char Code Char Code Char Code Char
32 (space) 51 3 70 F 89 Y 108 l
33 ! 52 4 71 G 90 Z 109 m
34 " 53 5 72 H 91 [ 110 n
35 # 54 6 73 I 92 \ 111 o
36 $ 55 7 74 J 93 ] 112 p
37 % 56 8 75 K 94 ^ 113 q
38 & 57 9 76 L 95 _ 114 r
39 ' 58 : 77 M 96 ` 115 s
40 ( 59 ; 78 N 97 a 116 t
41 ) 60 < 79 O 98 b 117 u
42 * 61 = 80 P 99 c 118 v
43 + 62 > 81 Q 100 d 119 w
44 , 63 ? 82 R 101 e 120 x
45 - 64 @ 83 S 102 f 121 y
46 . 65 A 84 T 103 g 122 z
47 / 66 B 85 U 104 h 123 {
48 0 67 C 86 V 105 i 124 |
49 1 68 D 87 W 106 j 125 }
50 2 69 E 88 X 107 k 126 ~
Programming and Problem Solving With Java 33
Example: Letter CountingTo access array by letter
// letterToInt: Returns 0 for 'A' or 'a', 1 for 'B'// or 'b', etc.static int letterToInt(char letter){ return ((int) Character.toLowerCase(letter)) - (int) 'a';}
...
frequency[letterToInt('B')]++;
0 1 2 3 4 23 24 25
Count
of A's
Count
of B's
Count
of C's
Count
of D's
Count
of E's
Count
of X's
Count
of Y's
Count
of Z's
...
Programming and Problem Solving With Java 34
Example: Letter CountingSteps for letter-counting
program Ask user for name of text
document; open the file Ask user for name of output
file; and open it Read in characters from input
file. For each letter, increment corresponding location in frequency array
Write frequency array to output file as a table
Close input and output files
Divide into 4 static methods main(): Initializes streams,
controls other methods letterToInt(): Converts 'A' or
'a' to 0, 'B' or 'b' to 1, etc. countLetters(): Counts
frequency of each letter in input stream, returns frequencies in an array
writeFrequency()Displays letter frequencies on output stream
Programming and Problem Solving With Java 35
Example: Letter CountingStructure chart
countLetters writeFrequency
main
letterToInt
Programming and Problem Solving With Java 36
Example: Letter CountingMethod main()
public static void main(String[] args) throws java.io.IOException { int[] frequency; String inputFileName, outputFileName;
// Open the input file inputFileName = Keyboard.readString("Input file: "); outputFileName = Keyboard.readString("Output file: "); // Check the input file File inputFile = new File(inputFileName); if (inputFile.exists() && inputFile.canRead()) { // Check the output file File outputFile = new File(outputFileName); if (!outputFile.exists() || outputFile.canWrite()) { // Initialize the input and output streams BufferedReader input = new BufferedReader(new FileReader(inputFile)); PrintWriter output = new PrintWriter(new BufferedWriter( new FileWriter(outputFile)));
Programming and Problem Solving With Java 37
Example: Letter CountingMethod main() (continued)
// Count the letter frequencies from the input file frequency = countLetters(input);
// Write the frequencies to the output file writeFrequency(output, frequency);
// Close the files input.close(); output.close(); } else { System.out.println("Can't write to " + outputFileName); } } else { System.out.println("Can't read from " + inputFileName); } }
Programming and Problem Solving With Java 38
Example: Letter CountingMethod countLetters()
// countLetters: Returns count of the number of times each// letter appears in the input file. All// letters are converted to upper case. All// non-letters are ignored. The input stream// should be initialized.static int[] countLetters(BufferedReader input)throws java.io.IOException{ char inputChar; int[] frequency = new int[LETTERS_IN_ALPHABET]; int inputCharAsInt;
// Read the file; count letter frequencies while ((inputCharAsInt = input.read()) != -1) { inputChar = (char) inputCharAsInt; if (Character.isUpperCase(inputChar) || Character.isLowerCase(inputChar)) { frequency[letterToInt(inputChar)]++; } }
return frequency;}
Programming and Problem Solving With Java 39
Example: Letter CountingMethod writeFrequency()
// writeFrequency: Writes the frequency array to the// output file as a table. The output// stream should be initialized.static void writeFrequency(PrintWriter output, int[] frequency){ output.println("Letter Frequency"); for (char letter = 'a'; letter <= 'z'; letter++) { output.println(" " + letter + " " + frequency[letterToInt(letter)]); }}
Programming and Problem Solving With Java 40
Example: Statistical AnalysisProgram to find average, high, and low of a series
of numbersWill read list of numbers from a fileFile format:
3415.12590.329009.1
Store the numbers in an arrayProgram will make the array just large enough to hold the
valuesOnce loaded, can go through array to find statistics
number of data values
data values
Programming and Problem Solving With Java 41
Example: Statistical AnalysisSample run of program
--- Data Analysis Program ---
Input file name: data.dat
(A)verage (H)igh (L)ow (D)isplay (Q)uit: aAverage: 5.64444
(A)verage (H)igh (L)ow (D)isplay (Q)uit: dStart position: 0End position: 80 3.41 8.12 5.63 2.14 9.35 7.46 5.37 6.48 3.2
(A)verage (H)igh (L)ow (D)isplay (Q)uit: hHigh value: 9.3
(A)verage (H)igh (L)ow (D)isplay (Q)uit: q
Programming and Problem Solving With Java 42
Example: Statistical AnalysisStructure chart
main
readDataFromFile
findAverage findMin findMax
doAnalysis
displayData
data
datam
inim
um
data
average datamaxim
um
data
data
Programming and Problem Solving With Java 43
Example: Statistical AnalysisMethod main()
public static void main(String[] args) throws java.io.IOException, java.text.ParseException { System.out.println("--- Data Analysis Program ---"); System.out.println();
// Get file name from user, initialize File object String fileName = Keyboard.readString("Input file: "); File inputFile = new File(fileName);
// Check input file if (inputFile.exists() && inputFile.canRead()) { BufferedReader input = new BufferedReader(new FileReader(inputFile)); double[] data = readDataFromFile(input); char selection;
do { System.out.println(); selection = Character.toLowerCase(Keyboard.readChar( "(A)verage (H)igh (L)ow (D)isplay (Q)uit: ", "ahldq"));
Programming and Problem Solving With Java 44
Example: Statistical AnalysisMethod main() (continued)
switch (selection) { case 'a': System.out.println("Average: " + findAverage(data)); break; case 'h': System.out.println("High value: " + findMax(data)); break; case 'l': System.out.println("Low value: " + findMin(data)); break; case 'd': displayData(data); break; case 'q': // do nothing break; default: System.out.println("Switch statement error"); break; } } while (selection != 'q'); } }}
Programming and Problem Solving With Java 45
Example: Statistical AnalysisTechnique for loading
an array Starting at one end, put
each value in next available position
Use a variable to keep track of next available position
Empty array
0 1 2 3 4 5 6 7
Array is full
'W''V''Y''D'
0 1 2 3 4 5 6 7
Array has data
'T''S''M''L''W''V''Y''D'
0 1 2 3 4 5 6 7
Programming and Problem Solving With Java 46
Example: Statistical AnalysisMethod readDataFromFile()
// readDataFromFile: Reads data from the file into the data // array static double[] readDataFromFile (BufferedReader input) throws java.io.IOException, java.text.ParseException { // Get a NumberFormat object NumberFormat formatter = NumberFormat.getInstance();
// Read number of values from stream int numValues = formatter.parse(input.readLine()).intValue();
// Define the array of the correct size double[] data = new double[numValues];
// Read data from stream into array for (int i = 0; i < numValues; i++) { data[i] = formatter.parse(input.readLine()).doubleValue(); }
return data; }
Programming and Problem Solving With Java 47
Example: Statistical AnalysisMethod findAverage()
// findAverage: Returns the mean (average) of all numbers in // the array, or zero if the array is empty. static double findAverage(double[] data) { double total = 0.0;
if (data.length == 0) { return 0.0; }
for (int i = 0; i < data.length; i++) { total = total + data[i]; } return total / data.length; }
Programming and Problem Solving With Java 48
Example: Statistical AnalysisHow to find the minimum value in an array
Scan the array, remembering the smallest value we've seen so far
At the beginning of the scan, the smallest we've seen so far is the first element
At the end of the scan, we'll know the smallest
intNum[0]
437
intNum[1]
12
intNum[2]
94
Programming and Problem Solving With Java 49
Example: Statistical AnalysisMethod findMin()
// findMin: Returns the minimum value of all numbers in the // array, or zero if the array is empty. static double findMin(double[] data) { double min;
if (data.length == 0) { return 0.0; }
min = data[0];
// Find min, where min is the minimum value in data[k] // for all k such that 0 £ k < n for (int i = 1; i < data.length; i++) { if (data[i] < min) { min = data[i]; } }
return min; }
Programming and Problem Solving With Java 50
Example: Statistical AnalysisMethod displayData()
// displayData: Lists the data in the array between locations // entered by the user. static void displayData(double[] data) throws java.io.IOException { int start = Keyboard.readInt("Start position: ", 0, data.length - 1); int finish = Keyboard.readInt("End position: ", start, data.length - 1);
for (int i = start; i <= finish; i++) { System.out.println(i + "\t" + data[i]); } }
Programming and Problem Solving With Java 51
Changing an Array's SizeCan't change array's size directlyIndirect way to do it:
Allocate a new array of the desired sizeCopy the elements from the old array to the new oneAssign the new array to the old array's variable
The standard Java class Vector (java.util.Vector) works this wayWorks like an arrayGrows automatically when it runs out of room
Programming and Problem Solving With Java 52
Changing an Array's SizeExample
// Allocate an array of 5 doublesdouble[] anArray = new double[5];
Let's put some data in the array.// Put 5 double values into the arrayanArray[0] = 1.2;anArray[1] = 3.2;anArray[2] = 6.5;anArray[3] = 4.1;anArray[4] = 8.3; // FULL!
Allocate a new array of 10 elements// Allocate an array of 10 doublesdouble[] newArray = new double[10];
Copy elements// Copy elements from the original array to the new oneSystem.arraycopy(anArray,0, newArray, 0, anArray.length);
Assign new array object to old array variable// Assign new array object to anArrayanArray = newArray;
Easy to write a method to do this (try it!)
Programming and Problem Solving With Java 53
Two-dimensional ArraysOne-dimensional
array has rowsTwo-dimensional
array has rowsand columns 0 1 2 3 4 5
0 1 2 3 4 5
0
1
2
3
One-dimensional array
Two-dimensional array
Programming and Problem Solving With Java 54
Two-dimensional Arrays: DefiningDefining a two-dimensional array
Very similar toone-dimensional
ExampleStore status of
traffic lights
N
S
EW
5th Ave
4th Ave
2nd Ave
1st Ave
1st S
t
2nd
St
3rd
St
5th
St
6th
St
7th
St
8th
St
3rd Ave
4th
St
1/10 mile
Megaville
final static int NUM_STREETS = 8;final static int NUM_AVENUES = 5;
final static int LIGHT_RED = 1;final static int LIGHT_GREEN = 2;final static int LIGHT_YELLOW = 3;final static int LIGHT_BROKEN = 4;
int[][] signal = new int[NUM_AVENUES][NUM_STREETS];
Programming and Problem Solving With Java 55
Two-dimensional Arrays: DefiningConceptual view of two-dimensional array
int[][] signal = new int[NUM_AVENUES][NUM_STREETS];
0 1 2 3 4 5
0
1
2
3
6 7
4
Columns
Row
s
Programming and Problem Solving With Java 56
Two-dimensional Arrays: UsingUsing a two-dimensional array
Access location with 2 subscripts: row# and column#
signal[1][4] = LIGHT_RED;
0 1 2 3 4 5
1
0
1
2
3
6 7
4
Columns
Row
s
Programming and Problem Solving With Java 57
Two-dimensional Arrays: UsingExamining all rows in a single column
How many traffic signals on Fourth St are green?int numberGreenLights = 0;for (int avenue = 0; avenue < NUM_AVENUES; avenue++){ if (signal[avenue][3] == LIGHT_GREEN) { numberGreenLights++; }}System.out.println("Green lights on Fourth Street: " + numberGreenLights);
0 1 2 3 4 5
0
1
2
3
6 7
4
Columns
Row
s
Programming and Problem Solving With Java 58
Two-dimensional Arrays: UsingExamining all columns in a single row
Which traffic signals on Second Ave are broken?for (int street = 0; street < NUM_STREETS; street++){
if (signal[1][street] == LIGHT_BROKEN) { System.out.println("Broken light: Second Ave and " + street + " Street"); }}
0 1 2 3 4 5
0
1
2
3
6 7
4
Columns
Row
s
Programming and Problem Solving With Java 59
Two-dimensional Arrays: AccessTo go through the entire array row by row
Hold the row number fixed at 0. Go through all the columns in row 0.
Hold the row number fixed at 1. Go through all the columns in row 1.
Continue for all other rows in the array.To go through the entire array column by column
Hold the column number fixed at 0. Go through all the rows in column 0.
Hold the column number fixed at 1. Go through all the rows in column 1.
Continue for all other columns in the array.
Programming and Problem Solving With Java 60
Two-dimensional Arrays: AccessCount all broken lights in city (process by rows)
int numberBrokenLights = 0;for (int avenue = 0; avenue < NUM_AVENUES; avenue++){ for (int street = 0; street < NUM_STREETS; street++) { if (signal[avenue][street] == LIGHT_BROKEN) { numberBrokenLights++; } }}System.out.println("Total broken lights: " + numberBrokenLights);
0 1 2 3 4 5
0
1
2
3
6 7
4
Columns
Row
s
Programming and Problem Solving With Java 61
Two-dimensional Arrays: AccessCount all broken lights in city (process by columns)
int numberBrokenLights = 0;for (int street = 0; street < NUM_STREETS; street++){ for (int avenue = 0; avenue < NUM_AVENUES; avenue++) { if (signal[avenue][street] == LIGHT_BROKEN) { numberBrokenLights++; } }}System.out.println("Total broken lights: " + numberBrokenLights);
0 1 2 3 4 5
0
1
2
3
6 7
4
Columns
Row
s
Reverse these
Programming and Problem Solving With Java 62
Two-dimensional Arrays: InitializeCan initialize two-dimensional array in definition
Example - define array to hold this
Syntaxdouble[][] x = { {12.2, 43.1, 95.4}, {59.3, 28.4, 64.3} };
Put each row within its own bracesThe number of columns can vary from row to row
Compiler defines each row with the given elements
Column 0 Column 1 Column 2
Row 1 12.2 43.1 95.3
Row 2 59.3 28.4 64.3
Programming and Problem Solving With Java 63
Two-dimensional Arrays: ParametersCan pass two-dimensional array to method
// countBrokenLights: Returns the number of brokenlights in// Megavillestatic int countBrokenLights(int[][] signal){ int numberBrokenLights = 0; for (int avenue = 0; avenue < signal.length; avenue++) { for (int street = 0; street < signal[avenue].length; street++) { if (signal[avenue][street] == LIGHT_BROKEN) { numberBrokenLights++; } } } return numberBrokenLights;}
Arrays are objects - so passed as an objectChanges made to array contents are persistentChanges made to array object are not persistent
Programming and Problem Solving With Java 64
Two-dimensional Arrays: SpreadsheetTwo-dimensional array example: spreadsheetFeatures
14 rows and 4 columns for numbersUser may
enter row and column headings
Program will compute total for each column after every change
January(0) February(1) March(2) April(3) Sales( 0) 112000 115100 117600 121300 Other inc( 1) 5000 5500 4500 3800 ( 2) 0 0 0 0 Materials( 3) -45000 -46500 -48000 -51000 Labor( 4) -48000 -48000 -48000 -48000 Administ( 5) -4000 -4000 -4000 -4000 Utilities( 6) -3500 -4200 -4400 -5100 Depreciat( 7) -2100 -2100 -2100 -2100 Mainten( 8) -3500 -3500 -3500 -3500 Other exp( 9) -2500 -2350 -4700 -2840 Taxes(10) -4200 -4200 -4200 -4200 (11) 0 0 0 0 (12) 0 0 0 0 (13) 0 0 0 0 TOTALS 4200 5750 3200 4360
+--- SpreadSheet ---| N) Number R) Row title C) Column title| H) Help D) Display Q) Quit| Enter selection:
Programming and Problem Solving With Java 65
Two-dimensional Arrays: SpreadsheetThree arrays needed
Row titles (1-dimensional)Column titles (1-dimensional)Rows and columns of
numbers (2-dimensional) 0 1 2 3
0123456789
1011121314
columnTitle
cell
0 1 2 3
0
0
0123456789
1011121314
rowTitle
Programming and Problem Solving With Java 66
Two-dimensional Arrays: Spreadsheet// This is a simple spreadsheet program. It has row// titles, column titles, and a 14 row by 4 column space for// numbers. When the user displays the spread sheet, totals are// computed for each column. User commands are selected by typing// their first letter. They are://// (N)umber - Enter a number into the spreadsheet// (R)ow title - Enter a row title// (C)olumn title - Enter a column title// (H)elp - Display help for commands// (Q)uit - Quit the program
import Keyboard;import TextMenu;import Format;
public class SpreadSheet extends TextMenu{ // Array size constants final static int MAX_ROWS = 14; final static int MAX_COLS = 4;
// Event codes final static int NUMBER_CMD = 1; final static int ROW_TITLE_CMD = 2; final static int COLUMN_TITLE_CMD = 3; final static int HELP_CMD = 4; final static int DISPLAY_CMD = 5;
Programming and Problem Solving With Java 67
Two-dimensional Arrays: SpreadsheetConstructor
// Constructor public SpreadSheet() { // Set menu title super("SpreadSheet");
// Initialize menu choices addSelection("Number", 'N', NUMBER_CMD); addSelection("Row title", 'R', ROW_TITLE_CMD); addSelection("Column title", 'C', COLUMN_TITLE_CMD); addSelection("Help", 'H', HELP_CMD); addSelection("Display", 'D', DISPLAY_CMD); addSelection("Quit", 'Q', TextMenu.QUIT);
// Initialize the spreadsheet clearSpreadSheet(); }
Programming and Problem Solving With Java 68
Two-dimensional Arrays: SpreadsheethandleEvent()
// handleEvent: If the given event code is defined, invokes // the action associated with that given event // code. Otherwise, does nothing public int handleEvent(int event) throws java.io.IOException { switch (event) { case NUMBER_CMD: enterNumber(); break; case ROW_TITLE_CMD: enterRowTitle(); break; case COLUMN_TITLE_CMD: enterColTitle(); break; case HELP_CMD: displayHelpInfo(); break; case DISPLAY_CMD: displaySpreadSheet(); break; } return event; }
Programming and Problem Solving With Java 69
Two-dimensional Arrays: SpreadsheetclearSpreadSheet()
// clearSpreadSheet: Puts zeros in all cells, sets all titles // to empty private void clearSpreadSheet() { int row, col;
// Clear row titles for (row = 0; row < MAX_ROWS; row++) { rowTitle[row] = ""; }
// Clear column titles for (col = 0; col < MAX_COLS; col++) { colTitle[col] = ""; }
// Clear cells for (row = 0; row < MAX_ROWS; row++) { for (col = 0; col < MAX_COLS; col++) { cell[row][col] = 0.0; } } }
Programming and Problem Solving With Java 70
Two-dimensional Arrays: SpreadsheetUser data entry
// enterNumber: Cell contains number user entered. private void enterNumber() throws java.io.IOException { int row = Keyboard.readInt("Row number: ", 0, MAX_ROWS - 1); int col = Keyboard.readInt("Column number: ", 0, MAX_COLS - 1); cell[row][col] = Keyboard.readDouble("Cell value: "); }
// enterRowTitle: Row title contains title user entered private void enterRowTitle() throws java.io.IOException { int row = Keyboard.readInt("Row number: ", 0, MAX_ROWS - 1); rowTitle[row] = Keyboard.readString("Row title: "); }
// enterColTitle: Column title contains title user entered private void enterColTitle() throws java.io.IOException { int col = Keyboard.readInt("Column number: ", 0, MAX_COLS - 1); colTitle[col] = Keyboard.readString("Column title: "); }
Programming and Problem Solving With Java 71
Two-dimensional Arrays: SpreadsheetwriteColumnTitles()
// writeColumnTitles: Displays the column titles across the top // of the spreadsheet private void writeColumnTitles() { System.out.print(Format.pad("", 14));
for (int col = 0; col < MAX_COLS; col++) { System.out.print(Format.padRight(colTitle[col], 11) + "(" + col + ")"); } System.out.println(); }
Programming and Problem Solving With Java 72
Two-dimensional Arrays: SpreadsheetdisplayColumnTotals()
// displayColumnTotals: Displays column totals across the bottom // of the spreadsheet private void displayColumnTotals() { double total;
System.out.print(Format.padRight("TOTALS", 14));
for (int col = 0; col < MAX_COLS; col++) { total = 0.0; for (int row = 0; row < MAX_ROWS; row++) { total = total + cell[row][col]; } System.out.print(Format.pad(total, 14, 2)); } System.out.println(); }
Programming and Problem Solving With Java 73
Two-dimensional Arrays: SpreadsheetdisplaySpreadSheet()
// displaySpreadSheet: Displays the spreadsheet, with row and // column titles, and column totals private void displaySpreadSheet() { System.out.println(); writeColumnTitles();
for (int row = 0; row < MAX_ROWS; row++) { System.out.print(Format.pad(rowTitle[row], 10) + "(" + Format.pad(row, 2) + ")"); for (int col = 0; col < MAX_COLS; col++) { System.out.print(Format.pad(cell[row][col], 14, 2)); } System.out.println(); } displayColumnTotals(); }
Programming and Problem Solving With Java 74
Two-dimensional Arrays: SpreadsheetdisplayHelpInfo()
// displayHelpInfo: Displays a brief description of all the // commands void displayHelpInfo() { System.out.println(" (N)umber - Enter a number"); System.out.println(" (R)ow title - Enter a row title"); System.out.println(" (C)olumn title - Enter a column title"); System.out.println(" (H)elp - Display help for " + "commands"); System.out.println(" (Q)uit - Quit the program"); }
// Instance variables private double[][] cell = new double [MAX_ROWS][MAX_COLS]; private String[] rowTitle = new String[MAX_ROWS]; private String[] colTitle = new String[MAX_COLS];
public static void main(String[] args) throws java.io.IOException { (new SpreadSheet()).run(); }}
Programming and Problem Solving With Java 75
Computer GraphicsComputers more graphical today than ever
Graphical user interfaces (GUI)Multimedia applications
2D graphics are simplest (and quite common)Problems with two dimensions
ClippingReal-world vs. screen coordinatesViewportsHidden lines
Problems with three dimensionsLightColorSurface contour
Programming and Problem Solving With Java 76
Computer GraphicsWill examine 2D graphicsWill use Java Frame object
Coordinates are x,y values (column, row)Coordinate 0,0 is at top left cornerCoordinate of bottom right corner depends on resolution
Draw with drawLine() method in java.awt.Graphics “Draws a line between the coordinates (x1,y1) and
(x2,y2) using the current colorParameters
x1 - the x coordinate of the start of the line y1 - the y coordinate of the start of the line x2 - the x coordinate of the end of the line y2 - the y coordinate of the end of the line” (JDK help)
Programming and Problem Solving With Java 77
Computer GraphicsCan store a shape as
a list of vertices (30, 0), (90, 0), (90, 80),
(120, 80), (60, 120), (0, 80), (30, 80), (30, 0)
Closed shape: first andlast vertices are same
Store vertices in 2-Darray
int[][] arrow = { {30, 0}, {90, 0}, {90, 80}, {120, 80}, {60, 120}, {0, 80}, {30, 80}, {30, 0}, {-1, -1} };
-1, -1 marks the end
00 30,0 90,0
90,80120,80
60,120
0,8030,80
Programming and Problem Solving With Java 78
Computer GraphicsProgram to draw an arrow
// Draws an arrow on a frame.
import java.awt.*;
public class DrawArrow extends Frame{ int[][] arrow = { {30, 0}, {90, 0}, {90, 80}, {120, 80}, {60, 120}, {0, 80}, {30, 80}, {30, 0}, {-1, -1} };
public DrawArrow() { super("Draw Arrow"); setSize(200, 200); show(); }
public void paint(Graphics g) { drawShape(g, arrow); }
Programming and Problem Solving With Java 79
Computer GraphicsProgram to draw an arrow (cont’d)
// drawShape: Draws the shape line by line // Note: -1, -1 is the end marker, and there must be at least // one x, y coordinate before the end marker. private void drawShape(Graphics g, int[][] shape) { // Move to the first position int currentX = shape[0][0]; int currentY = shape[0][1];
for (int i = 1; shape[i][0] != -1; i++) { g.drawLine(currentX, currentY, shape[i][0], shape[i][1]); currentX = shape[i][0]; currentY = shape[i][1]; } } public static void main(String[] args) { new DrawArrow(); }}
Programming and Problem Solving With Java 80
Computer Graphics: ManipulationShape manipulations
Translate (move)Scale (change size)Rotate
Translating a shapeTo move r horizontally: add r to each x-valueTo move s vertically, add s to each y-value
00
r
s
Programming and Problem Solving With Java 81
Computer Graphics: ManipulationScaling a shape
Relative to origin (0, 0)Multiply x values by
horizontal scaling factorMultiply y values by
vertical scaling factorIf shape not at origin
Translate to originScale shapeTranslate back
00
1.5
1.25
Programming and Problem Solving With Java 82
Computer Graphics: ManipulationRotating a shape degrees
is degrees in radiansConverting between degrees and radians
Compute new verticesnewX = x cos - y sin new Y = y cos + x sin
Assumes shape at origin
00
20°= 0.35 radians
dr
360
2
rd
2
360
Programming and Problem Solving With Java 83
Computer Graphics: MatricesScaling and rotation require shape to be at origin
Doing separate rotation, scaling, and translation (2 times) steps is inefficient
Better to do all calculations once: use matricesMatrix
2D array of numbersExamples
1 2
3 4181 5 2 4
0 6
0 25
7
. .
.
.
Programming and Problem Solving With Java 84
Computer Graphics: MatricesMatrix multiplication A x B
# columns in A == # rows in BResult has # rows in A, # columns in B
Example
7 56 41 2
3 2 4 17 1 5 3
3 x 2 2 x 4
=
Must match
Size of result
56 19 53 2246 16 44 1817 4 14 7
3 x 4
C A B A B A Bi j i j i j i n n j, , , , , , ,... 1 1 2 2
Programming and Problem Solving With Java 85
Computer Graphics: MatricesTranslation matrix
r units horizontal s units vertical
Scaling matrixhorizontal factor f vertical factor g
Rotation matrixangle radians
newX newY x y
f
g1 1
0 0
0 0
0 0 1
newX newY x y
r s
1 1
1 0 0
0 1 0
1
newX newY x y1 1
0
0
0 0 1
cos sin
sin cos
Programming and Problem Solving With Java 86
Computer Graphics: Demo ProgramDemonstration of transformation, scaling, rotation
Programming and Problem Solving With Java 87
Computer Graphics: Demo Program// Demonstration of some simple graphics routines - SLOW APPROACH.
import java.awt.*;
public class Draw2Arrows extends Frame{ int[][] arrow = { {30, 0}, {90, 0}, {90, 80}, {120, 80}, {60,120}, {0, 80}, {30, 80}, {30, 0}, {-1, -1} }; int[][] bigArrow;
public Draw2Arrows() { super("Draw 2 Arrows"); setSize(500, 400); // Copy arrow to bigArrow bigArrow = new int[arrow.length][2]; for (int row = 0; row < arrow.length; row++) { for (int col = 0; col < 2; col++) { bigArrow[row][col] = arrow[row][col]; } } // Translate bigArrow scale(bigArrow, 2, 3); rotate(bigArrow, 1); // 1 radian is about 57 degrees translate(bigArrow, 350, 20); show(); }
Programming and Problem Solving With Java 88
Computer Graphics: Demo Program public void paint(Graphics g) { drawShape(g, arrow); drawShape(g, bigArrow); } // drawShape: Draws the shape line by line // Note: -1, -1 is the end marker, and there must be at least // one x, y coordinate before the end marker. private void drawShape(Graphics g, int[][] shape) { // Move to the first position int currentX = shape[0][0]; int currentY = shape[0][1];
for (int i = 1; shape[i][0] != -1; i++) { g.drawLine(currentX, currentY, shape[i][0], shape[i][1]); currentX = shape[i][0]; currentY = shape[i][1]; } }
Programming and Problem Solving With Java 89
Computer Graphics: Demo Program // matrixMult: Multiplies an array of vertices by a 3x3 matrix, // giving a new array of vertices private void matrixMult(double[] a, double[][] b, double[] result) { for (int col = 0; col < 3; col++) { result[col] = 0.0; for (int k = 0; k < 3; k++) { result[col] = result[col] + a[k] * b[k][col]; } } }
Programming and Problem Solving With Java 90
Computer Graphics: Demo Program // transformShape: Transforms the shape by the given transform // matrix private void transformShape(int[][] shape, double[][] transformMatrix) { double[] oldPosition = { 0, 0, 1 }; double[] newPosition = { 0, 0, 1 };
for (int i = 0; shape[i][0] != -1; i++) { oldPosition[0] = shape[i][0]; oldPosition[1] = shape[i][1]; matrixMult(oldPosition, transformMatrix, newPosition); shape[i][0] = (int) Math.round(newPosition[0]); shape[i][1] = (int) Math.round(newPosition[1]); } }
// scale: Scales the shape by the given factors private void scale(int[][] shape, double xFactor, double yFactor) { double[][] scaleMat = { { xFactor, 0, 0 }, { 0, yFactor, 0 }, { 0, 0, 1 } }; transformShape(shape, scaleMat); }
Programming and Problem Solving With Java 91
Computer Graphics: Demo Program // rotate: Rotates the shape counterclockwise by the given // radians private void rotate(int[][] shape, double radians) { double[][] rotateMat = { { Math.cos(radians), Math.sin(radians), 0 }, { -Math.sin(radians), Math.cos(radians), 0 }, { 0, 0, 1 } }; transformShape(shape, rotateMat); }
// translate: Moves shape to the right and up by the given // amounts private void translate(int[][] shape, int moveX, int moveY) { double[][] translateMat = { { 1, 0, 0 }, { 0, 1, 0 }, { moveX, moveY, 1 } }; transformShape(shape, translateMat); }
public static void main(String[] args) { new Draw2Arrows(); }}
Programming and Problem Solving With Java 92
Computer Graphics: Demo ProgramSlow approach: program does this for each vertex
Scale by 2 horizontally, 5 vertically
Rotate by 1 radian
Translate by 500 horizontally, 20 vertically
newX newY x y1 1
2 0 0
0 5 0
0 0 1
newX newY x y1 1
1 1 0
1 1 0
0 0 1
cos( ) sin( )
sin( ) cos( )
newX newY x y1 1
1 0 0
0 1 0
500 20 1