Java Coding 6 David Davenport Computer Eng. Dept.,

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Example - The.
Java Coding OOP David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Towards Event-driven programming &
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 Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Java Coding 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Decisions, decisions…!
Java Coding 3 David Davenport Computer Eng. Dept.,
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
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.
Review: OOP & Arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. …from CS101.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
Java Coding 4 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Method madness.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Java Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Computational Algorithms David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. lightning introduction.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Java Coding 6 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Collections.
Java Coding OOP_3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Some important Java interfaces +
Arrays Chapter 13 How to do the following with a one dimensional array: Declare it, use an index.
Java Coding 8 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Object-Oriented Design Examples.
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.
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chapter 7.
Java Coding 6 David Davenport Computer Eng. Dept.,
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Array in C# Array in C# RIHS Arshad Khan
Java Coding – part 2 David Davenport Computer Eng. Dept.,
[ 4.00 ] [ Today’s Date ] [ Instructor Name ]
© 2016 Pearson Education, Ltd. All rights reserved.
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
Foundations of Programming: Arrays
Java Coding 3 – part2 David Davenport Computer Eng. Dept.,
Chapter 7 Part 1 Edited by JJ Shepherd
Java Coding 3 David Davenport Computer Eng. Dept.,
Java Coding 8 David Davenport Computer Eng. Dept.,
Arrays in C.
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Objects First with Java CITS1001
Java How to Program, Late Objects Version, 10/e
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
int [] scores = new int [10];
Java Programming Arrays
Arrays in Java What, why and how Copyright Curt Hill.
Introduction To Programming Information Technology , 1’st Semester
Object Oriented Programming in java
BIT115: Introduction to Programming
Java Coding 6-extra David Davenport Computer Eng. Dept.,
CS2011 Introduction to Programming I Arrays (I)
int [] scores = new int [10];
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
7 Arrays.
Suggested self-checks: Section 7.11 #1-11
Data Structures & Algorithms
Java Coding 4 (part2) David Davenport Computer Eng. Dept.,
Java Coding 6_part3 David Davenport Computer Eng. Dept.,
Consider Write a program that prompts a user to enter the number of students and then, their names and grades. The program will then outputs the average.
How do you do the following?
Arrays.
Java Coding 6 David Davenport Computer Eng. Dept.,
Java Coding 5 – Part 2 David Davenport Computer Eng. Dept.,
Presentation transcript:

Java Coding 6 David Davenport Computer Eng. Dept., Collections – using arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. email: david@bilkent.edu.tr Last update: 11/12/2017 ~now only arrays (ArrayLists now in separate file!) Few minor tweaks! Previously: 12/12/2016 ~added more detailed slides for ArrayLists 6/12/2012 ~split original into two parts, (1) ArrayLists & fixed size arrays, (2) variable sized arrays.

IMPORTANT… Students… Instructors… This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an email saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.

Not so easy collections… Arrays

Not-so-easy Collections Arrays Common data structure All elements of same type Are Objects in Java Basis of ArrayList class! Each element has unique successor & predecessor (except first & last.) Data structure – grouping of data elements ? Data structure where elements are of different types? In Java they are Objects so everything you know about objects (&references) applies! Reason they are so common is easy to implement at low-level, even in hardware. Elements are stored sequentially from a starting address. Since the elements are the same, the size the occupy is the same. Hence, computing the address of any element from its index is easy! Difference btw ArrayList & Array? + ArrayList can have any number of any type of element + Array can only have one type of element, and number is fixed at creation and cannot be changed. Problem is how to implement ArrayList’s using lower-level Arrays… 3 6 5 1 10 2 4 grades Name for entire structure Each element identified by an index (label/subscript)

Array Syntax (1) Arrays are Objects, so Array size cannot be changed after creation! Arrays are Objects, so declare variable then instantiate Note use of square brackets! type[] variableName ; variableName = new type[ noOfElements ]; Other examples double[] heights; String[] names; boolean[] flags; Doctor[] docs; … names = new String[100] Note: indexes (label/subscripts) always begin at zero and increase. Last one is noOfElements-1 If also have int[] results; what does results = grades; do? Alternative is results = grades.clone(); -- but shallow clone by default! IMPORTANT: number of elements in array cannot be changed after array is created! Note: Initializer lists… (maybe leave until later?) int[] grades = { 10, 3, 6, 5, 1}; For some reason can only use this when declaring array, not afterwards! Useful for constants such as String[] daysOfWeek = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”}; 3 6 5 1 10 2 4 grades int[] grades; grades = new int[5];

Array Syntax (2) Referring to an individual element variableName[index] where index is a literal, named constant, variable, or expression. examples grades[0] grades[ i] grades[1] grades[ i+1] names[99] names[ FIRST] Can do anything with individual element that you can do with normal variable of the same type. Note: index must be between 0 & noOfElements in array – 1, else ArrayIndexOutOfBoundsException! grades[0] = 10; grades[1] = grades[0] + 2; System.out.println( grades[0]); names[99] = scan.nextLine();

Processing all elements e.g. Printing contents of array grades System.out.println( grades[0] ); System.out.println( grades[1] ); : for ( int i = 0; i < ___________; i++) System.out.println( grades[i] ); Cannot print array directly System.out.println( grades): // doesn’t work! So, must do it element by element… ? How many elements does the array have? - write number, e.g. 5 - define named constant final int NOOFELEMENTS = 5; (or variable) & use when creating array & processing it - use the length property… length is property (not method!) of arrays – returns number of elements the array has. Use this example as pattern for processing all elements of an array. e.g. summing them to find average, finding minimum, whether in ascending order or not, … for ( int i = 0; i < grades.length; i++) System.out.println( grades[i] ); Trying to say… // can use alternate for syntax for ( int k : grades ) System.out.println( k); for each value in grades print the value

Easy Problem – again? Read in a set of positive integer values and then print out a table showing the average, each of the values and their difference from the average. Example output… umm… must remember all the values we read in in order to print the table. Average is 5 Value Diff -------------- 10 5 3 -2 6 1 1 -4 -------------- Algorithm 1. read set of values (how? Fixed number, e.g. 4, ask user how many?, use sentinel?) 2. compute average of set of values (?divide by zero error?) 3. print table using average & set of values Can store int’s directly in array (unlike ArrayLists!) ? Leave as exercise for students to do. ? Possible lab assignment? ? Now in book? See following slides for design using methods! can use arrays directly ( not restricted to object-types like ArrayLists! )

Easy Problem using arrays! Printing table of differences from average 1. read set of values 2. compute average of set of values 3. print table of differences using average & set of values Steps 2 & 3 are straightforward For step 1 need to know how many values Fixed, e.g. 5 Ask user Use sentinel - but length of array is fixed! Using sentinel is problem since size of array cannot be changed after it has been created. Catch-22 ! We will come back to that problem later… For now, demo straightforward implementation.

Easy Problem with Methods! Identify method signatures from algorithm int[] readSetOfValues() 1. read set of values double computeAverage( int[] setOfValues) 2. compute average of set of values Have already written the algorithm & identified information flowing from one statement to another. This gave us our data requirements. Now want to implement each step as a method call. Identify information flowing into and out of a step. The output of a step is the method result. The inputs to a step are the method parameters. Note: If parameters are object-type, then they can act as input and outputs too. e.g. Step 1 might be done like this… void readSetOfValues( int[] setOfValues) but requires the array to be instantiated with the correct number of elements before calling (this method then simply changes the values of the elements). void printTable( double average, int[] setOfValues) 3. print table of differences using average & set of values Data Requirements: average – double setOfValues – int[] Note: Object-type parameters can act as outputs too!

Arrays of objects Array contains only references to objects Person[] contacts; contacts = new Person[5]; Still need to create actual objects contacts[0] = new Person( “David”, 21); contacts[1] = new Person( “Gunes”, 18); Array element is object, so call its methods as normal – variableName.methodName(parameters) Caution: do not attempt to access non-existent object! Since elements can be any sort of object, they may be other arrays – giving multi-dimensional arrays! 1 2 3 4 contacts David 21 Gunes 18 contacts[0].getName() contacts[4].getName()

Arrays of arrays… Multi-dimensional arrays grid { int[5][3] } 1 2 3 4 Arrays can hold any type including arrays… (and arrays of arrays of arrays…) Can create arrays of any dimension. Note: All elements must still be of same type, e.g int, double, Person, Date, etc. Automatically filled with default value for type, e.g. 0 or null. Can have ragged arrays; not all elements have to be there! grid[0][1] grid[4][2] int[][] grid; grid = new int[5][3]; for ( int i = 0; i < 5; i++) for ( int j = 0; j < 3; j++) System.out.println( grid[i][j] );