Download presentation
Presentation is loading. Please wait.
Published byMelinda Carson Modified over 8 years ago
1
Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 8 Arrays One-dimensional Arrays Two-dimensional Arrays Computer Graphics
2
Programming and Problem Solving With Java 2 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 Value 1 Value 2 Value 3 Output Program Variable 1 Variable 2 Variable 3
3
Programming and Problem Solving With Java 3 One-dimensional Arrays Program may read lots of values But reads and processes one at a time Value 1 Value 2 Value 3 Output Program Variable 1 Value 4 Value 5 Value n...
4
Programming and Problem Solving With Java 4 One-dimensional Arrays Some programs need to store many values Example: read many values, display in reverse order Tedious 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...
5
Programming and Problem Solving With Java 5 One-dimensional Arrays Alternative: use an array Define one array variable Store many values in that single variable Access the values in any order in the array Value 1 Value 2 Value 3 Output Program Array variable Value 4 Value 5 Value n...
6
Programming and Problem Solving With Java 6 One-dimensional Arrays Difference between simple and array variables Simple variable holds a single value Array variable holds several values
7
Programming and Problem Solving With Java 7 Arrays: Defining To define an array variable int[] intNum; Must then create an array object intNum = new int[3]; Creates an array object with 3 integers Can do in one step int[] intNum = new int[3];
8
Programming and Problem Solving With Java 8 Arrays: Defining After defining the array, access elements by subscript int[] intNum = new int[3]; intNum[0] = 437; intNum[2] = intNum[0] - 343; intNum[1] = (intNum[2] - 10) / 7;
9
Programming and Problem Solving With Java 9 Arrays: Defining Example 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: 425 Second number: 39 Third number: -125 The numbers are: 425 39 -125 intNum.length is size of array
10
Programming and Problem Solving With Java 10 Arrays: Defining Example: Store rainfall data Array must store 18 floating-point values double[] rainFall = new double[18]; Better approach -- use a constant static final int NUM_YEARS = 18;... double[] rainFall = new double[NUM_YEARS]; Can now assign values to positions in array rainFall[0] = 30.55; rainFall[1] = 23.94; rainFall[2] = 18.32;...
11
Programming and Problem Solving With Java 11 Arrays: Defining Array of String objects Define array static final int NUM_NAMES = 5; String[] name = new String[NUM_NAMES]; Assign values name[0] = "Smith"; name[1] = "Jones"; name[2] = "Miller"; name[3] = "Lui"; name[4] = "Gonzales"; Display values for (int nameNumber = 0; nameNumber < name.length; nameNumber++) { System.out.println(nameNumber + ": " + name[nameNumber]); } Output 0: Smith 1: Jones 2: Miller 3: Lui 4: Gonzales
12
Programming and Problem Solving With Java 12 Arrays: Defining Array of Money objects Define array Money[] quarterlySales = new Money[4]; Assign values quarterlySales[0] = new Money(400, 00); // first quarter quarterlySales[1] = new Money(450, 00); // second quarter quarterlySales[2] = new Money(375, 00); // third quarter quarterlySales[3] = new Money(425, 00); // fourth quarter Display values for (int quarter = 0; quarter < 4; quarter++) { System.out.println("Sales for quarter " + (quarter + 1) + ": " + quarterlySales[quarter]); } Output Sales for quarter 1: 400.00 Sales for quarter 2: 450.00 Sales for quarter 3: 375.00 Sales for quarter 4: 425.00
13
Programming and Problem Solving With Java 13 Arrays: Defining Initial 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(); Output 0 0 0 0 0 0 0 0 0 Initial value of object array (String, Money,...) is null static 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(); Output null null null null null
14
Programming and Problem Solving With Java 14 Arrays: Using Array 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 variable
15
Programming and Problem Solving With Java 15 Arrays: Using Example: Compute average rainfall for all 18 years Set up the rainFall array double[] rainFall = new double[18]; rainFall[0] = 30.55; rainFall[1] = 23.94;... Sum all the amounts - first (long!) approach total = 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) approach double total = 0.0; for (int year = 0; year < rainFall.length; year++) { total = total + rainFall[year]; } Display the average System.out.println("Average rainfall is " + (total / rainFall.length));
16
Programming and Problem Solving With Java 16 Arrays: Using Access outside the array double[] rainFall = new double[18]; rainFall[19] = -5; Run-time error java.lang.ArrayIndexOutOfBoundsException: 19 at Test.main(Test.java) Make sure array access is within bounds 01234567891011121314151617??
17
Programming and Problem Solving With Java 17 Arrays: Using Displaying values of array Must display individual values for (int year = 0; year < rainFall.length; year++) { System.out.println(rainFall[year]); } Reading values into an array Must read individual values for (int year = 0; year < rainFall.length; year++) { rainFall[year] = Keyboard.readDouble("Enter rainfall for year " + year + ": "); }
18
Programming and Problem Solving With Java 18 Arrays: Initializing Can 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 operator Initialize array of objects Strings String[] name = {"Smith", "Jones", "Miller"}; Other objects Money 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
19
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
20
Programming and Problem Solving With Java 20 Arrays: Copying Two ways to make a copy of an array Use for statement to copy individual elements // Make an array int[] originalArray = { 7, 4, 5, 2 }; // Define another int[] aCopy = new int[originalArray.length]; // Copy individual elements for (int element = 0; element < originalArray.length; element++) { aCopy[element] = originalArray[element]; } Use System.arraycopy() method // Make an array int[] originalArray = { 7, 4, 5, 2 }; // Define another int[] 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 COPY
21
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
22
Programming and Problem Solving With Java 22 Arrays: Parameters Can 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 parameter static 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 + ": "); }
23
Programming and Problem Solving With Java 23 Arrays: Parameters Method can return array object Useful when method allocates the array object // Reads rain fall data from user into rainFall array and // returns the array static 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; }
24
Programming and Problem Solving With Java 24 Arrays: Parameters What'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 + ": "); }
25
Programming and Problem Solving With Java 25 Example: 1-column Spreadsheet Use of the program --- One-column SpreadSheet --- (D)isplay (E)nter (Q)uit: e Position: 3 Data: 59.5 (D)isplay (E)nter (Q)uit: e Position: 5 Data: 18.0 (D)isplay (E)nter (Q)uit: d 3 59.5 5 18.0 Total 77.5 (D)isplay (E)nter (Q)uit: e Position: 3 Data: 18.6 (D)isplay (E)nter (Q)uit: d 3 18.6 5 18.0 Total 36.6 (D)isplay (E)nter (Q)uit: q
26
Programming and Problem Solving With Java 26 Example: 1-column Spreadsheet Code // 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();
27
Programming and Problem Solving With Java 27 Example: 1-column Spreadsheet Code (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;
28
Programming and Problem Solving With Java 28 Example: 1-column Spreadsheet Code (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'); }
29
Programming and Problem Solving With Java 29 Example: Letter Counting Program to count letter frequency in a text file Program asks for input and output files Input file name: frogs.txt Output file name: frogs.out
30
Programming and Problem Solving With Java 30 Example: Letter Counting Use 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 file Translate 'B' into 1 Increment array at position 1
31
Programming and Problem Solving With Java 31 Example: Letter Counting Two 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'; }
32
Programming and Problem Solving With Java 32 Example: Letter Counting Example: '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
33
Programming and Problem Solving With Java 33 Example: Letter Counting To 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')]++;
34
Programming and Problem Solving With Java 34 Example: Letter Counting Steps 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
35
Programming and Problem Solving With Java 35 Example: Letter Counting Structure chart
36
Programming and Problem Solving With Java 36 Example: Letter Counting Method 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)));
37
Programming and Problem Solving With Java 37 Example: Letter Counting Method 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); }
38
Programming and Problem Solving With Java 38 Example: Letter Counting Method 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; }
39
Programming and Problem Solving With Java 39 Example: Letter Counting Method 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)]); }
40
Programming and Problem Solving With Java 40 Example: Statistical Analysis Program to find average, high, and low of a series of numbers Will read list of numbers from a file File format: 3 415.12 590.32 9009.1 Store the numbers in an array Program will make the array just large enough to hold the values Once loaded, can go through array to find statistics number of data values data values
41
Programming and Problem Solving With Java 41 Example: Statistical Analysis Sample run of program --- Data Analysis Program --- Input file name: data.dat (A)verage (H)igh (L)ow (D)isplay (Q)uit: a Average: 5.64444 (A)verage (H)igh (L)ow (D)isplay (Q)uit: d Start position: 0 End position: 8 03.4 18.1 25.6 32.1 49.3 57.4 65.3 76.4 83.2 (A)verage (H)igh (L)ow (D)isplay (Q)uit: h High value: 9.3 (A)verage (H)igh (L)ow (D)isplay (Q)uit: q
42
Programming and Problem Solving With Java 42 Example: Statistical Analysis Structure chart
43
Programming and Problem Solving With Java 43 Example: Statistical Analysis Method 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"));
44
Programming and Problem Solving With Java 44 Example: Statistical Analysis Method 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'); }
45
Programming and Problem Solving With Java 45 Example: Statistical Analysis Technique 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
46
Programming and Problem Solving With Java 46 Example: Statistical Analysis Method 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; }
47
Programming and Problem Solving With Java 47 Example: Statistical Analysis Method 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; }
48
Programming and Problem Solving With Java 48 Example: Statistical Analysis How 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
49
Programming and Problem Solving With Java 49 Example: Statistical Analysis Method 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; }
50
Programming and Problem Solving With Java 50 Example: Statistical Analysis Method 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]); }
51
Programming and Problem Solving With Java 51 Changing an Array's Size Can't change array's size directly Indirect way to do it: Allocate a new array of the desired size Copy the elements from the old array to the new one Assign the new array to the old array's variable The standard Java class Vector (java.util.Vector) works this way Works like an array Grows automatically when it runs out of room
52
Programming and Problem Solving With Java 52 Changing an Array's Size Example // Allocate an array of 5 doubles double[] anArray = new double[5]; Let's put some data in the array. // Put 5 double values into the array anArray[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 doubles double[] newArray = new double[10]; Copy elements // Copy elements from the original array to the new one System.arraycopy(anArray,0, newArray, 0, anArray.length); Assign new array object to old array variable // Assign new array object to anArray anArray = newArray; Easy to write a method to do this (try it!)
53
Programming and Problem Solving With Java 53 Two-dimensional Arrays One-dimensional array has rows Two-dimensional array has rows and columns
54
Programming and Problem Solving With Java 54 Two-dimensional Arrays: Defining Defining a two-dimensional array Very similar to one-dimensional Example Store status of traffic lights 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];
55
Programming and Problem Solving With Java 55 Two-dimensional Arrays: Defining Conceptual view of two-dimensional array int[][] signal = new int[NUM_AVENUES][NUM_STREETS];
56
Programming and Problem Solving With Java 56 Two-dimensional Arrays: Using Using a two-dimensional array Access location with 2 subscripts: row# and column# signal[1][4] = LIGHT_RED;
57
Programming and Problem Solving With Java 57 Two-dimensional Arrays: Using Examining 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);
58
Programming and Problem Solving With Java 58 Two-dimensional Arrays: Using Examining 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"); }
59
Programming and Problem Solving With Java 59 Two-dimensional Arrays: Access To 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.
60
Programming and Problem Solving With Java 60 Two-dimensional Arrays: Access Count 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);
61
Programming and Problem Solving With Java 61 Two-dimensional Arrays: Access Count 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); Reverse these
62
Programming and Problem Solving With Java 62 Two-dimensional Arrays: Initialize Can initialize two-dimensional array in definition Example - define array to hold this Syntax double[][] x = { {12.2, 43.1, 95.4}, {59.3, 28.4, 64.3} }; Put each row within its own braces The number of columns can vary from row to row Compiler defines each row with the given elements
63
Programming and Problem Solving With Java 63 Two-dimensional Arrays: Parameters Can pass two-dimensional array to method // countBrokenLights: Returns the number of brokenlights in // Megaville static 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 object Changes made to array contents are persistent Changes made to array object are not persistent
64
Programming and Problem Solving With Java 64 Two-dimensional Arrays: Spreadsheet Two-dimensional array example: spreadsheet Features 14 rows and 4 columns for numbers User may enter row and column headings Program will compute total for each column after every change
65
Programming and Problem Solving With Java 65 Two-dimensional Arrays: Spreadsheet Three arrays needed Row titles (1-dimensional) Column titles (1-dimensional) Rows and columns of numbers (2-dimensional)
66
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;
67
Programming and Problem Solving With Java 67 Two-dimensional Arrays: Spreadsheet Constructor // 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(); }
68
Programming and Problem Solving With Java 68 Two-dimensional Arrays: Spreadsheet handleEvent() // 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; }
69
Programming and Problem Solving With Java 69 Two-dimensional Arrays: Spreadsheet clearSpreadSheet() // 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; }
70
Programming and Problem Solving With Java 70 Two-dimensional Arrays: Spreadsheet User 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: "); }
71
Programming and Problem Solving With Java 71 Two-dimensional Arrays: Spreadsheet writeColumnTitles() // 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(); }
72
Programming and Problem Solving With Java 72 Two-dimensional Arrays: Spreadsheet displayColumnTotals() // 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(); }
73
Programming and Problem Solving With Java 73 Two-dimensional Arrays: Spreadsheet displaySpreadSheet() // 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(); }
74
Programming and Problem Solving With Java 74 Two-dimensional Arrays: Spreadsheet displayHelpInfo() // 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(); }
75
Programming and Problem Solving With Java 75 Computer Graphics Computers more graphical today than ever Graphical user interfaces (GUI) Multimedia applications 2D graphics are simplest (and quite common) Problems with two dimensions Clipping Real-world vs. screen coordinates Viewports Hidden lines Problems with three dimensions Light Color Surface contour
76
Programming and Problem Solving With Java 76 Computer Graphics Will examine 2D graphics Will use Java Frame object Coordinates are x,y values (column, row) Coordinate 0,0 is at top left corner Coordinate 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 color Parameters 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)
77
Programming and Problem Solving With Java 77 Computer Graphics Can 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 and last vertices are same Store vertices in 2-D array 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
78
Programming and Problem Solving With Java 78 Computer Graphics Program 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); }
79
Programming and Problem Solving With Java 79 Computer Graphics Program 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(); }
80
Programming and Problem Solving With Java 80 Computer Graphics: Manipulation Shape manipulations Translate (move) Scale (change size) Rotate Translating a shape To move r horizontally: add r to each x-value To move s vertically, add s to each y-value
81
Programming and Problem Solving With Java 81 Computer Graphics: Manipulation Scaling a shape Relative to origin (0, 0) Multiply x values by horizontal scaling factor Multiply y values by vertical scaling factor If shape not at origin Translate to origin Scale shape Translate back
82
Programming and Problem Solving With Java 82 Computer Graphics: Manipulation Rotating a shape degrees is degrees in radians Converting between degrees and radians Compute new vertices newX = x cos - y sin new Y = y cos + x sin Assumes shape at origin
83
Programming and Problem Solving With Java 83 Computer Graphics: Matrices Scaling 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 matrices Matrix 2D array of numbers Examples
84
Programming and Problem Solving With Java 84 Computer Graphics: Matrices Matrix multiplication A x B # columns in A == # rows in B Result has # rows in A, # columns in B Example
85
Programming and Problem Solving With Java 85 Computer Graphics: Matrices Translation matrix r units horizontal s units vertical Scaling matrix horizontal factor f vertical factor g Rotation matrix angle radians
86
Programming and Problem Solving With Java 86 Computer Graphics: Demo Program Demonstration of transformation, scaling, rotation
87
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(); }
88
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]; }
89
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]; }
90
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); }
91
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(); }
92
Programming and Problem Solving With Java 92 Computer Graphics: Demo Program Slow approach: program does this for each vertex Scale by 2 horizontally, 5 vertically Rotate by 1 radian Translate by 500 horizontally, 20 vertically
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.