Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 8 Arrays One-dimensional Arrays Two-dimensional Arrays Computer Graphics.

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 10 Introduction to Arrays
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Syntax Primitive data types Operators Control statements.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
IE 212: Computational Methods for Industrial Engineering
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2006 Pearson Education, Inc. All rights reserved Arrays.
A First Book of ANSI C Fourth Edition
Chapter 8 Arrays and Strings
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 Pearson Education, Inc. All rights reserved Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Overview Excel is a spreadsheet, a grid made from columns and rows. It is a software program that can make number manipulation easy and somewhat painless.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays. Topics to be Covered... Arrays ◦ Declaration ◦ Assigning values ◦ Array manipulation using loops Multi-dimensional arrays ◦ 2D arrays ◦ Declaration.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Java Programming Language Lecture27- An Introduction.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays Chapter 7.
Chapter VII: Arrays.
Chapter 7: User-Defined Functions II
7 Arrays.
7 Arrays.
Functions continued.
Arrays.
Presentation transcript:

Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 8 Arrays One-dimensional Arrays Two-dimensional Arrays Computer Graphics

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

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...

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...

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...

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

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];

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;

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: intNum.length is size of array

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;...

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

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: Sales for quarter 2: Sales for quarter 3: Sales for quarter 4:

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  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 14 Arrays: Using  Array variable + subscript = single element static final int NUM_YEARS = 18;... double[] rainFall = new double[NUM_YEARS]; double amount; amount = ; rainFall[0] = 30.55; rainFall[1] = 23.94;...  Treat rainFall[0] just like any double variable

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));

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 ??

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 + ": "); }

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

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

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

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

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 + ": "); }

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; }

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 + ": "); }

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 Total 77.5 (D)isplay (E)nter (Q)uit: e Position: 3 Data: 18.6 (D)isplay (E)nter (Q)uit: d Total 36.6 (D)isplay (E)nter (Q)uit: q

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();

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;

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'); }

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

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

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'; }

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' =  Result is 1

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')]++;

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

Programming and Problem Solving With Java 35 Example: Letter Counting  Structure chart

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)));

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); }

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; }

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)]); }

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:  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 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: (A)verage (H)igh (L)ow (D)isplay (Q)uit: d Start position: 0 End position: (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 42 Example: Statistical Analysis  Structure chart

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"));

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'); }

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

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; }

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; }

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

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; }

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]); }

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

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!)

Programming and Problem Solving With Java 53 Two-dimensional Arrays  One-dimensional array has rows  Two-dimensional array has rows and columns

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];

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];

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;

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);

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"); }

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.

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);

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

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

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

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

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)

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: 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(); }

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; }

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; }

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: "); }

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(); }

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(); }

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(); }

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(); }

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

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)

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

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); }

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(); }

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

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

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

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

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

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

Programming and Problem Solving With Java 86 Computer Graphics: Demo Program  Demonstration 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 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