940 likes | 1.12k Views
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.
E N D
Chapter 8Arrays 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 Variable 2 Output Value 2 Variable 3 Value 3 Programming and Problem Solving With Java
One-dimensional Arrays • Program may read lots of values • But reads and processes one at a time Value 1 Program Value 2 Value 3 Variable 1 Output Value 4 Value 5 ... Value n Programming and Problem Solving With Java
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 Program Value 1 Variable 1 Value 2 Variable 2 Value 3 Variable 3 Output Value 4 Variable 4 Value 5 Variable 5 ... ... Value n Variable n Programming and Problem Solving With Java
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 Program Value 2 Value 3 Array variable Output Value 4 Value 5 ... Value n Programming and Problem Solving With Java
One-dimensional Arrays • Difference between simple and array variables • Simple variable holds a single value • Array variable holds several values Programming and Problem Solving With Java
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]; Programming and Problem Solving With Java
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; Programming and Problem Solving With Java
Arrays: Defining First number: 425 Second number: 39 Third number: -125 The numbers are: 425 39 -125 • 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]); • } • } • } intNum.length is size of array Programming and Problem Solving With Java
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; • ... Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 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 Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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)); Programming and Problem Solving With Java
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 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ?? Programming and Problem Solving With Java
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 + ": "); • } Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 + ": "); • } • } Programming and Problem Solving With Java
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; • } Programming and Problem Solving With Java
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 + ": "); • } • } Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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(); Programming and Problem Solving With Java
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; Programming and Problem Solving With Java
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'); • } • } Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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'; • } 'B' 1 Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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')]++; Programming and Problem Solving With Java
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 Example: Letter Counting Programming and Problem Solving With Java
Example: Letter Counting • Structure chart Programming and Problem Solving With Java
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))); Programming and Problem Solving With Java
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); • } • } Programming and Problem Solving With Java
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; • } Programming and Problem Solving With Java
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)]); • } • } Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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 • 0 3.4 • 1 8.1 • 2 5.6 • 3 2.1 • 4 9.3 • 5 7.4 • 6 5.3 • 7 6.4 • 8 3.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 Programming and Problem Solving With Java
Example: Statistical Analysis • Structure chart Programming and Problem Solving With Java
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")); Programming and Problem Solving With Java
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'); • } • } • } Programming and Problem Solving With Java
Example: Statistical Analysis • Technique for loadingan array • Starting at one end, put each value in next available position • Use a variable to keep track of next available position Programming and Problem Solving With Java
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; • } Programming and Problem Solving With Java
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; • } Programming and Problem Solving With Java
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 Programming and Problem Solving With Java
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; • } Programming and Problem Solving With Java
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]); • } • } Programming and Problem Solving With Java