CS1083 Week 2: Arrays, ArrayList

Similar documents
Final Exam Practice. Partial credit will be awarded.

This exam is open book. Each question is worth 3 points.

Chapter 4: Writing Classes

CS163/164 Final Exam Study Session

CS111: PROGRAMMING LANGUAGE II

Anatomy of a Class Encapsulation Anatomy of a Method

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

CS1004: Intro to CS in Java, Spring 2005

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Chapter 4 Defining Classes I

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CS 101 Fall 2006 Midterm 3 Name: ID:

CS 302 Week 9. Jim Williams

AP CS Unit 7: Interfaces. Programs

Robots. Byron Weber Becker. chapter 6

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Do not start the test until instructed to do so!

Bjarne Stroustrup. creator of C++

CPSC 219 Extra review and solutions

Object Oriented Programming. Java-Lecture 1

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

COMP 202. Programming With Arrays

Week 3 Classes and Objects

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Review: Array Initializer Lists

Software and Programming 1

Assignment 1 due Monday at 11:59pm

Classes. Classes as Code Libraries. Classes as Data Structures

Introduction to Java Unit 1. Using BlueJ to Write Programs

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

APCS Semester #1 Final Exam Practice Problems

CITS1001 week 4 Grouping objects

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

CS111: PROGRAMMING LANGUAGE II

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

CS 101 Spring 2007 Midterm 2 Name: ID:

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

16. Give a detailed algorithm for making a peanut butter and jelly sandwich.

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

AP Computer Science Unit 1. Programs

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Spring 2010 Java Programming

Java Review. Fundamentals of Computer Science

1 Short Answer (10 Points Each)

Question 1 [20 points]

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

Programming Exercise 7: Static Methods

01. Which of the following statement describes dynamic resizing as is applies to the ArrayList class?

Lesson 26: ArrayList (W08D1)

Controls Structure for Repetition

Recitation: Loop Jul 7, 2008

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Introduction to Functional Programming in Java 8

Computational Expression

Programming II (CS300)

CS 200 Using Objects. Jim Williams, PhD

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Classes Classes 2 / 35

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Programming with Java

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012

Chapter 2. Elementary Programming

An exception is simply an error. Instead of saying an error occurred, we say that an.

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

H212 Introduction to Software Systems Honors

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Back public class HelloWorld { public static void main ( String arg[] ) { Front Basic Setup. Java Quick Sheet. ~ 35 Flashcards. 1 AP CS - Rodriguez

Introduction to Programming Using Java (98-388)

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

Example Program. public class ComputeArea {

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

COMP 110 Programming Exercise: Simulation of the Game of Craps

CS 201, Fall 2016 Sep 28th Exam 1

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

Computational Expression

Java Coding 3. Over & over again!

CSCI 1103: File I/O, Scanner, PrintWriter

Intro to Computer Science II

Computer Science is...

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Programming in the Large II: Objects and Classes (Part 1)

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Midterms Save the Dates!

CSC 1051 Algorithms and Data Structures I. Final Examination December 17, Name:

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Transcription:

CS1083 Week 2: Arrays, ArrayList mostly review David Bremner 2018-01-08

Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics

Multiple references to an array d o u b l e prices [ ] = { 1. 0, 1. 0, 1. 0, 1. 0 ; d o u b l e sale []= prices ; Sale1 f o r ( i n t i=0; i< sale. length ; i++){ sale [ i ] = sale [ i ] / 2 ; System. out. println ( prices [ 2 ] ) ; prices Called aliasing. What is the right way to impliment this? Sale2 sale 1.0 1.0 1.0 1.0

Bounds Checking In Java (unlike C or C++), price[i] is equivalent to 1 i f ( i < 0 i>= price. length ) { 2 t h r o w new ArrayOutOfBoundsException ( ) ; 3 e l s e { 4 return element i from array price 5 For the moment, line 2 means Crash What is the result of prices[prices.length]

Passing arrays What does this program display? public class ArrayStatic{ static void s(int t[]) { t[0] = 3; t[0] = 6; t[2] = 9; public static void main(string[] args){ int t[]={0, 1, 2; t[0] = 1; t[1] = 2; t[2] = 3; s(t); for (int i = 0; i < 3; i++) System.out.print(t[i] + " "); ArrayStatic

partially filled arrays Goals keep track of list of scores compute average

partially filled arrays Goals keep track of list of scores compute average p r i v a t e i n t count ; Scores1 p r i v a t e d o u b l e [ ] scores ; p u b l i c Scores1 ( i n t max ) { count = 0 ; scores = new d o u b l e [ max ] ;

Adding elements p u b l i c v o i d add ( d o u b l e score ) { Scores1 scores [ count ] = score ; count++; encapsulation Why a mutator / private instance variables? What could go wrong if we made them public?

Computing the average p u b l i c d o u b l e getaverage ( ) { d o u b l e sum =0.0; f o r ( i n t i=0; i<count ; i++){ sum += scores [ i ] ; r e t u r n sum/count ; class design Is it reasonable to call this an accessor? Why, or why not? How could we make this method faster while preserving the same API? Scores2

Encapsulation and class design Encapsulation is about a well defined API The designer of a library controls what operations are permitted This is necessary for the library designer to guarantee correctness Generally make instance variables private and provide getters and setters. Mutators allow sanity checking input.

Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics

2D Arrays Recall that you can declare an array of anything. Even an array of arrays i n t [ ] [ ] grid ; As usual, the array of arrays must be created grid=new i n t [ 1 0 ] [ ] And each element (which is in turn an array) must also be created. f o r ( i n t i=0; i <10; i++) grid [ i]=new i n t [ i +1];

2D Arrays Recall that you can declare an array of anything. Even an array of arrays i n t [ ] [ ] grid ; As usual, the array of arrays must be created grid=new i n t [ 1 0 ] [ ] And each element (which is in turn an array) must also be created. f o r ( i n t i=0; i <10; i++) grid [ i]=new i n t [ i +1];

2D Arrays Recall that you can declare an array of anything. Even an array of arrays i n t [ ] [ ] grid ; As usual, the array of arrays must be created grid=new i n t [ 1 0 ] [ ] And each element (which is in turn an array) must also be created. f o r ( i n t i=0; i <10; i++) grid [ i]=new i n t [ i +1];

2D Arrays Recall that you can declare an array of anything. Even an array of arrays i n t [ ] [ ] grid ; As usual, the array of arrays must be created grid=new i n t [ 1 0 ] [ ] And each element (which is in turn an array) must also be created. f o r ( i n t i=0; i <10; i++) grid [ i]=new i n t [ i +1];

And then can be used What is the output?

And then can be used for (int i=0; i<10; i++) { System.out.println(); What is the output?

And then can be used for (int i=0; i<10; i++) { for (int j=0; j<grid[i].length; j++) { if (j>0) System.out.print(grid[i][j]); System.out.println(); What is the output?

And then can be used for (int i=0; i<10; i++) { for (int j=0; j<grid[i].length; j++) { if (j>0) System.out.print(" "); System.out.print(grid[i][j]); System.out.println(); What is the output?

And then can be used for (int i=0; i<10; i++) { for (int j=0; j<grid[i].length; j++) { if (j>0) System.out.print(" "); System.out.print(grid[i][j]); System.out.println(); What is the output?

The normal case In general, every row is the same length, and we can take the shortcut grid=new i n t [ 1 0 ] [ 1 0 ] ; And then the same code yields: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

The normal case In general, every row is the same length, and we can take the shortcut grid=new i n t [ 1 0 ] [ 1 0 ] ; And then the same code yields: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics

Reading PBM Files P1 3 3 111 101 111 PBM Format Using Scanner: nextint, next Read header and initialize Read bits

Reading PBM Files P1 3 3 111 101 111 PBM Format Using Scanner: nextint, next Read header and initialize Read bits

Reading PBM Files P1 3 3 111 101 111 PBM Format Using Scanner: nextint, next Read header and initialize Read bits

Reading PBM Files P1 3 3 111 101 111 PBM Format Using Scanner: nextint, next Read header and initialize Read bits

Reading PBM Files P1 3 3 111 101 111 PBM Format Using Scanner: nextint, next Read header and initialize Read bits

Instance Variables PBM public class PBM { private int[][] bits; private int rows,columns;.

Constructor PBM() throws IOException{ Scanner sc = new Scanner(System.in);

Constructor PBM() throws IOException{ Scanner sc = new Scanner(System.in); if (!sc.next().equals("p1")) throw new IOException("Format error");

Constructor PBM() throws IOException{ Scanner sc = new Scanner(System.in); if (!sc.next().equals("p1")) throw new IOException("Format error"); columns=sc.nextint(); rows=sc.nextint();

Constructor PBM() throws IOException{ Scanner sc = new Scanner(System.in); if (!sc.next().equals("p1")) throw new IOException("Format error"); columns=sc.nextint(); rows=sc.nextint(); bits=new int[rows][columns];

Constructor PBM() throws IOException{ Scanner sc = new Scanner(System.in); if (!sc.next().equals("p1")) throw new IOException("Format error"); columns=sc.nextint(); rows=sc.nextint(); bits=new int[rows][columns]; for (int i=0; i< rows; i++){ String line=sc.next();

Constructor PBM() throws IOException{ Scanner sc = new Scanner(System.in); if (!sc.next().equals("p1")) throw new IOException("Format error"); columns=sc.nextint(); rows=sc.nextint(); bits=new int[rows][columns]; for (int i=0; i< rows; i++){ String line=sc.next(); for (int j=0; j<columns; j++)

Constructor PBM() throws IOException{ Scanner sc = new Scanner(System.in); if (!sc.next().equals("p1")) throw new IOException("Format error"); columns=sc.nextint(); rows=sc.nextint(); bits=new int[rows][columns]; for (int i=0; i< rows; i++){ String line=sc.next(); for (int j=0; j<columns; j++) bits[i][j]=line.charat(j)-'0';

tostring public String tostring(){ String result=""; return result;

tostring public String tostring(){ String result=""; for (int i=0; i< rows; i++){ result +="\n"; return result;

tostring public String tostring(){ String result=""; for (int i=0; i< rows; i++){ for (int j=0; j<columns; j++){ result +="\n"; return result;

tostring public String tostring(){ String result=""; for (int i=0; i< rows; i++){ for (int j=0; j<columns; j++){ if (bits[i][j]==1) result += "*"; else result += " "; result +="\n"; return result;

Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics

ArrayList class In java.util LL5.6 Stores list of objects Allows objects to be added and removed Implemented using an array Resized as needed Uses generic type

Generics ArrayList<String> list = new ArrayList<String >(); Type of elements in collections specifed in <> Only objects of specifed type can be added to collection Objects removed already have correct type (don t need to cast) For primitive types use wrapper class (e.g. Integer)

Working with ArrayList Create list of objects of Passenger class, which stores passenger name, id, weight, and luggage weight. ArrayList<Passenger> list = new ArrayList<Passenger >(); list. add ( new Passenger ( Pete, 5 0, 2 0 ) ) ; list. add ( new Passenger ( Fred, 8 0, 3 0 ) ) ;

Iterating Through List Could do like this: f o r ( i n t i=0; i<list. size ( ) ; i++){ System. out. println ( list. get ( i ) ) ; Better to use for-each loop

For-Each Loop Works with objects that implement Iterable interface We ll see interfaces soon ArrayList implements Iterable Also works with regular arrays For processing all elements of collecton (list or array) LL6.4

For-Each Loops f o r ( Passenger p : list ){ System. out. println ( p ) ; i n t [ ] a = {2, 13, 6, 8 ; i n t sum = 0 ; f o r ( i n t val : a ){ sum += val ;

Variable Length Parameter Lists If a small number of objects of same type to be passed to method, don t need to use array LL8.5 mean1 = average ( 4 2, 69, 3 7 ) ; mean2 = average ( 3 5, 4 3, 9 3, 4 0, 2 1, 7 5 ) ;

Variable Length Parameter Lists p u b l i c d o u b l e average ( i n t... list ){ d o u b l e result = 0. 0 ; i f ( list. length!= 0){ i n t sum = 0 ; f o r ( i n t num : list ) sum += num ; result = ( d o u b l e ) sum/list. length ; r e t u r n result ; Parameters automatically put into array