Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 #25 20123T1.

Slides:



Advertisements
Similar presentations
MiniDraw Testing COMP 102 # T1
Advertisements

© Xiaoying Gao, Peter Andreae COMP :1 Term test Grade Marks No of students “A” range 36 ~45 53 “B” range29.25~ “C” range 22.5~2941 “D” range
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Arrays COMP 102.
Arrays Chapter 6 Chapter 6.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Java Unit 9: Arrays Declaring and Processing Arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Review COMP 102 #
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays with meaningful indices.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington More Interfaces.
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.
Problem Solving using the Java Programming Language May 2010 Mok Heng Ngee Day 5: Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Patterns with.
2011-T1 Lecture 13 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Files COMP 102.
David Streader & Peter Andreae Computer Science Victoria University of Wellington Copyright: David Streader, Victoria University of Wellington Objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays with meaningful indices.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington More Interfaces.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington “For each” & Patterns with.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Event-driven Input TextFields,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Classes, Objects, Fields,
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 103 #
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW AI for games: min-max search COMP #
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Classes and.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Fields, Constructors.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on Files COMP 102 # 14.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 7.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Creating Objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More 2D arrays COMP 102 #27.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
2011-T1 Lecture 12 School of Engineering and Computer Science, Victoria University of Wellington  Rashina Hoda and Peter Andreae COMP 102 Rashina Hoda.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.
ARRAYS Multidimensional realities Image courtesy of
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Arrays COMP 102 # T1.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Dealing with Files COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More on ArrayLists COMP 102.
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.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Event-driven Input COMP.
Yanal Alahmad Java Workshop Yanal Alahmad
Writing to a File Open a File Wrap it in a new PrintStream object.
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
Chapter 8 Slides from GaddisText
1D Arrays and Lots of Brackets
Presentation transcript:

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1

© Peter Andreae COMP :2 Menu Assignment 8: BalloonGame and Genealogy Some more array details 2D arrays Administration Did you miss the test? Friday is the last day to drop the course (unless you have special permission from the dean) Marks for the test will not be back in time for Friday 

© Peter Andreae COMP :3 Assignment 8 Same ideas as last week: arrays and ArrayLists BalloonGame Array of Balloon objects Balloon is defined for you You have to implement the interface and the game logic Fill the array with balloons Respond to the mouse: find the balloon they clicked on check if it is touching any other balloon recompute the score Doing things to each element of the array Comparing an element to every other element Program design: breaking program into multiple methods

© Peter Andreae COMP :4 Assignment 8 Genealogy ArrayList of Person objects Person is defined for you You have to implement methods to search the “database” of Persons Load the ArrayList from a file Searching the ArrayList for items Doing things to each element of the array Program design: breaking program into multiple methods

© Peter Andreae COMP :5 Arrays as Parameters You can pass an array as a parameter to a method : int[ ] myNums = new int[ ] { 3,5,7,11,13,17,19,23,29,31,37,43,47}; UI.println(“Prime sum = ” + this.sum(myNums)); this.makeSquare(myNums); : public int sum(int[] a) { int s = 0; for (int i = 0; i < a.length; i++) s += a[i]; return s; } public void makeSquare(int[] a) { for (int i = 0; i < a.length; i++) a[i] = a[i] * a[i]; } a: myNums:

© Peter Andreae COMP :6 Comparing arrays. Be careful when comparing arrays (as with all objects) int[ ] a = new int[ ]{ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 43, 47}; int[ ] b = new int[ ]{ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 43, 47}; int[ ] c = b; if (a == b)..  ?? if (b == c)..  ?? if (a.equals(b) )..  ?? if (Arrays.equals(a, b) )..  ?? if (this.arrayEquals(a, b) )..  ?? public boolean arrayEquals(int[] a, int[] b) { if ( a.length != b.length ) { return false; } for (int i = 0; i < a.length; i++) { if ( a[i] != b[i] ) { return false; } } return true; }

© Peter Andreae COMP :7 Main method main takes an array of strings as a parameter: Can be used to provide “command line inputs” to a program, eg. the name of a file to process. May be optional: public static void main(String[ ] args) { String fname; if ( args.length > 0 ) { fname = args[0]; } else { fname = UIFileChooser.open("Data files"); } try { Scanner scan = new Scanner (new File(fname)); while (scan.hasNext()) { … } } catch (IOException e){ …… } } > java Plotter mynumbers.txt

© Peter Andreae COMP :8 2D Data XOX O MonTueWedThuFriSatSun IDA1A2A3A

© Peter Andreae COMP :9 2D arrays: Creating 2D arrays require two indices Declaring and creating: int[ ] [ ] marks = new int [200][4]; ChessPiece[ ][ ] board = new ChessPiece [8][8]; Color[ ][ ] image = new Color [100][150]; int[ ][ ] matrix = new int [ ][ ]{{2, 4, 2},{4, 8, 4}, {2, 4, 2}}; Which is the row and which is the column? You choose! Choose your variable names carefully.

© Peter Andreae COMP :10 2D arrays: accessing Assigning and accessing: marks[10][3] = 72; board[row][col] = board[row][col-1]; board[row][col-1] = null; for (int row=0; row<100; row++){ for (int col=0; col<100; col++){ image[row][col] = image[row][col].darker(); } In Java, can’t use commas image[row, col]

© Peter Andreae COMP :11 2D arrays 2D arrays are actually arrays of arrays: int[ ] [ ] marks = new int[200] [4]; is the same as int[ ] [ ] marks = new int[200] [ ]; for (int i = 0; i<200; i++){ marks[i] = new int[4]; }

© Peter Andreae COMP :12 2D arrays: length Number of rows and columns in a 2D array? int[ ] [ ] marks = new int[200] [4]; marks.length  number of rows (200) marks[row].length  number of columns (4)

© Peter Andreae COMP :13 2D arrays Can have non-square arrays: int[ ] [ ] table = new int[7] [ ]; for (int row = 0; row<7; row++){ table[row] = new int[row+1]; }

© Peter Andreae COMP :14 Processing 2D arrays Typically use nested for loops to process each item public void printTable( String[ ][ ] grades){ for (int row=0; row< grades.length; row++){ for (int col=0; col< grades[row].length; col++){ UI.printf(" %-2s ", grades[row][col]); } UI.println(); } } public void printTable( String[ ][ ] grades){ for (String[ ] row : grades){ for (String grade : row){ UI.printf(" %-2s ", grade); } UI.println(); } } '-' flag means left justified A+ B- A- B B+ C A B- A D A+ A A- B+ B+ B A A- C+ C+

© Peter Andreae COMP :15 Drawing a 2D array public void drawBoard(ChessPiece[ ][ ] board){ int rows = board.length; int cols = board[0].length; for (int row=0; row<rows; row++){ int y = this.top+this.size*row; for (int col=0; col<cols; col++) { int x = this.left+this.size*col; UI.setColor( (row%2==col%2) ? Color.gray : Color.white); UI.fillRect(x, y, this.size, this.size); if (board[row][col] !=null) { board[row][col].draw(x, y); } }♔♕♗♖♘♙♚♛♜♝♞♟ } UI.drawRect(x, y, this.size*rows, this.size*cols); } ♖ ♔♘ ♗ ♙♜ ♝ ♚ ♜ Shorthand for: if (row%2==col%2) { UI.setColor(Color.gray); } else { UI.setColor(Color.white); }

© Peter Andreae COMP :16 Printing a table with headers public void printTable(long[ ] IDs, String[ ][ ] grades){ int rows = grades.length; int cols = grades[0].length; UI.print(" ID |"); for (int col=0; col<cols; col++) { UI.printf(" A%d |", col); } UI.println(); for (int col=-1; col<cols; col++) { UI.print("----+"); } UI.println(); for (int row=0; row<rows; row++){ UI.printf("%4d|", IDs[row]) for (int col=0; col<cols; col++) { UI.printf(" %-2s |", grades[row][col]); } UI.println(); } for (int col=-1; col<cols; col++) { UI.print("----+"); } UI.println(); } ID | A1 | A2 | A3 | A4 | | A+ | B- | A- | B | 3052| B+ | C | A | B- | 3029| A | D | A+ | A | 3172| A- | B+ | B+ | B | 3094| A | A- | C+ | C+ | Assumes all rows same length

© Peter Andreae COMP :17 Processing multiple arrays public double[ ][ ] matrixAdd(double[ ][ ] a, double[ ][ ] b){ int rows = a.length; int cols = a[0].length; if (b.length!=rows || b[0].length!=cols) { return null; } double[ ][ ] ans = new double[rows][cols]; for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++){ ans[row][col] = a[row][col] + b[row][col]; } return ans; } =

© Peter Andreae COMP :18 Saving a 2D array to a file Write the grade table to a file: A B B+ A- B B+ B- C+ A A- B- B+ Writing the dimensions of the array first will help. Three people with 4 assignments each or Four people with 3 assignments each or Six people with 2 assignments each

© Peter Andreae COMP :19 Saving a 2D array to a file Writing the dimensions in the file helps: public void saveTable( String[][] grades, String fileName){ try{ PrintStream file =new PrintStream(new File(fileName)); int rows = grades.length; int cols = grades[0].length; file.println(rows + " " + cols); for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++){ file.println(grades[row][col]); } }catch(IOException e){UI.println("Table saving failed: "+e);} } As long as each element is a token, could also write each row on one line. Print number of rows and columns on first line of file.

© Peter Andreae COMP :20 Saving a 2D array to a file Alternate design: assume file has been opened elsewhere and passed as argument use "foreach" because not modifying the array. public void saveTable( String[ ][ ] grades, PrintStream file){ file.println(grades.length + " " + grades[0].length); for (String[ ] row : grades){ for (String gr : row){ file.println(gr); } Note, you could pass System.out to the method to make it print to the terminal window! (useful for debugging)

© Peter Andreae COMP :21 Loading 2D array from a file Assume the file has the dimensions as the first two tokens: public String[ ][ ] loadTable( ){ try { Scanner sc = new Scanner(new File(UIFileChooser.open())); int rows =sc.nextInt(); int cols = sc.nextInt(); String[ ][ ] ans = new String[ rows ][ cols ]; for (int row=0; row<rows; row++){ for (int col=0; col<cols; col++){ ans[row][col] = sc.next(); } return ans; } catch(IOException e){UI.out.println("Table loading failed: "+e);} return null; }

© Peter Andreae COMP :22 Loading 2D array from a file Alternate, assuming scanner is passed as argument array is stored in a field public void loadTable(Scanner sc ){ this.dataArray = new String[ sc.nextInt() ] [ sc.nextInt() ]; for (int row=0; row<ans.length; row++){ for (int col=0; col<ans[row].length; col++){ this.dataArray[row][col] = sc.next(); }