C OMP 110 A RRAYS Instructor: Jason Carter. 2 O UTLINE for loops Arrays.

Slides:



Advertisements
Similar presentations
Chapter 21 Implementing lists: array implementation.
Advertisements

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Basic Java Constructs and Data Types – Nuts and Bolts
Chapter 8: Arrays.
Graphics Graphics Java Vectors Java Enumeration Graphical Spreadsheets
Programming Languages and Paradigms The C Programming Language.
J A V A SHASHI BHUSHAN. MAIN ISSUES Object Oriented Concepts Examples FAQs.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
C OMP 110/401 C OLLECTION K INDS Instructor: Prasun Dewan.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
C OMP 401 I NTRODUCTION Instructor: Prasun Dewan.
C OMP 110 M ORE T YPES Instructor: Jason Carter. 2 P RIMITIVE T YPES int, double, boolean, long, short, float, byte char.
C OMP 401 D YNAMIC D ISPATCH AND A BSTRACT M ETHODS Instructor: Prasun Dewan.
J AVA AND V ARIABLES. O VERVIEW Declaring a Variable Primitive Types Java Keywords Reference Variables Object Declaration and Assignment Objects and Garbage.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables) IS-A Relationship –human IS-A.
Arrays Chapter 6 Chapter 6.
Comp 114 Foundations of Programming Instructor: Prasun Dewan.
Arrays –Collections (Set, Database, History) Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables)
Inheritance and IS-A Inheritance –inheriting ancestor’s traits –inheriting benefactor’s assets –inheriting instance members( methods/variables) IS-A Relationship.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Scanning Scanning image for text. Scanning frequencies for radio stations. Finding words in a sentence Finding identifiers, operators, in a program char.
ObjectEditor Prasun Dewan Comp 114. ObjectEditor Automatic user-interface generation. You only write computation code Separate object to do I/O Main just.
Comp 114 Foundations of Programming Instructor: Prasun Dewan (Pr  sün Divän)
Object-based Scanning Redo the scanning solution Monolithic, single class solution –does UI and scanning No reuse of code Another scanning problem to.
Java Unit 9: Arrays Declaring and Processing Arrays.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
C OMP 110 L OOPS A DVANCED Instructor: Prasun Dewan.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
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.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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 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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
C OMP 401: C ONSTRUCTORS AND P OINTERS Instructor: Prasun Dewan (FB 150,
Introduction to Programming G50PRO University of Nottingham Unit 8 : Methods 2 - Arrays Paul Tennent
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) public static void main(String[]
C OMP 110/401 D OCUMENTATION : C OMMENTS Instructor: Prasun Dewan.
Primitive data Week 3. Lecture outcomes Primitive data – integer – double – string – char – Float – Long – boolean Declaration Initialisation Assignments.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
C OMP 401 A DVANCED G ENERICS Instructor: Prasun Dewan.
1 CSC 201: Computer Programming I Lecture 2 B. S. Afolabi.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.
Object-based Scanning Redo the scanning solutions Monolithic, single class solutions –does UI and scanning No reuse of code.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
int [] scores = new int [10];
INLS 560 – S TRINGS Instructor: Jason Carter. T YPES int list string.
Vector program patterns Vectors contain many elements, so loops are common. Counted processing // Print the first 3 elements. for (int i = 0; i < 3; i++)
Arrays What is an array… –A data structure that holds a set of homogenous elements (of the same type) –Associate a set of numbers with a single variable.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
CMSC 150 ARRAYS CS 150: Fri 10 Feb Motivation  Consider a list of your contact addresses: String Zero = String.
Chapter 9 Introduction to Arrays Fundamentals of Java.
A DVANCED P ROGRAMMING C HAPTER 8: A RRAYS Dr Shahriar Bijani Spring 2016.
C OMP 401 D YNAMIC D ISPATCH AND V IRTUAL AND A BSTRACT M ETHODS Instructor: Prasun Dewan.
Information and Computer Sciences University of Hawaii, Manoa
Comp 401 Dynamic Dispatch and Virtual and Abstract Methods
Introduction to Java Programming
An Introduction to Java – Part I, language basics
Comp 110/401 Documentation: Comments
Recitation 10 November 3, 2011.
Introduction to java Part I By Shenglan Zhang.
More on iterations using
Presentation transcript:

C OMP 110 A RRAYS Instructor: Jason Carter

2 O UTLINE for loops Arrays

3 S TRINGS = C HAR S EQUENCES JohnF.Kennedy hello String {sequences of characters}

4 S TRING P ROCESSING Prints each character on a separate line int i = 0; while (i < s.length()) { System.out.println(s.charAt(i)); i++; }

5 D ISSECTING A L OOP int i = 0; while (i < s.length()) { System.out.println(s.charAt(i)); i++; } Loop Condition Loop Body

6 F INGER - GRAINED D ISSECTION // String s declared and initialized earlier int i = 0; while (i < s.length()) { System.out.println(s.charAt(i)); i++; } Loop Condition Loop Body Resetting Loop Variable Initializing Loop Variable for (int i=0; i<s.length(); i++) System.out.println ( s.charAt(i));

7 M EANING OF F OR L OOP for ( S1; E; S2) S3 for ( S1; E; S2) S3 for ( ; E; S2) S3 for ( ; E; S2) S3 for ( ; E;) S3 for ( ; E;) S3 for ( ;;) S3 for ( ;;) S3 S1; while (E) { S3; S2; } S1; while (E) { S3; S2; } while (E) { S3; S2; } while (E) { S3; S2; } while (E) { S3; } while (E) { S3; } S1; while ( true ) { S3; S2; } S1; while ( true ) { S3; S2; }

8 O THER P REDEFINED T YPES AS S EQUENCES IntSequence {sequences of integers} DoubleSequence {sequences of doubles} JFKFDRJCBCRRGB StringSequence {sequences of string}

9 S EQUENCES OF P ROGRAMMER -D EFINED T YPES loan1loan2loan3 LoanSequence Loan[] temperature1 TemperatureSequence Temperature [] temperature2temperature3 temperature1temperature2 Array Types Arrays Array Element

10 O THER S EQUENCES AS A RRAY T YPES int[] double[] JFKFDRJCBCRRGB String[]

11 I NITIALIZING A RRAY D ECLARATION int[] assignmentScores = {100, 98, 99, 100, 90, 80}; Array Type Array Literal Element Type Array Variable double[] gpas = {3.8, 3.1, 3.7, 3.1, 3.6, 3.9}; String[] initials = {“JFK, “FDR”, “JC”, “BC”, “RR”, “GB”}; JFKFDRJCBCRRGB

12 I NITIALIZING A RRAY D ECLARATION S YNTAX [] = {, …, } Loan [] loans = { new ALoan(100000), new AnotherLoan (100)};

13 A RRAY T YPES H AVE V ARIABLE S IZE int[] int[] assignmentScores = {100, 98, 99, 100, 90, 80}; assignmentScores = {60, 40, 50}; assignmentScores

14 A RRAY O PERATIONS String[] initials = {“JFK, “FDR”, “JC”, “BC”, “RR”, “GW”, “WW”}; JFKFDRJCBCRRGWWW initials.length6 public named constant initials[0]JFK initials[initials.length-1]WW initials[initials.length]ArrayIndexOutOfBounds Exception initials[0] = “HT” initials[initials.length] = “HT”ArrayIndexOutOfBounds Exception Array instance size fixed! HT

15 U NINITIALIZING A RRAY D ECLARATION int[] assignmentScores; assignmentScores = {60, 40, 50}; assignmentScores null

16 A RRAY E LEMENTS U NINITIALIZED int [] assignmentScores = new int [3]; assignmentScores 000

17 O BJECT A RRAY E LEMENTS U NINITIALIZED String[] initials = new String[3]; initials null

18 E XAMPLE

19 GET S TRINGS () static String[] getStrings() { System.out.println("Number of Strings:"); int numElements = Console.readInt(); System.out.println("Please enter " + numElements + " strings"); String[] strings = new String[numElements]; for ( int elementNum = 0; elementNum < numElements; elementNum++) strings[elementNum] = Console.readString(); return strings; } Variable

20 PRINT () static void print(String[] strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.length; elementNum++) System.out.println(strings[elementNum]); System.out.println("******************"); } String array of arbitrary dimension

21 MAIN () public static void main(String[] args){ String[] names = getStrings(); String command = Console.readString(); while (command.length() > 0 && command.charAt(0) != ‘q’) { if (command.charAt(0) == 'p') print(names); command = Console.readString(); } Must test that length is at least 1 before accessing char at position 0 No need to test length here

22 A NOTHER E XAMPLE

23 V ARIABLE -S IZE C OLLECTION filled part unfilled part current size maximum size

24 3 James Dean Joe Doe Jane Smith sizearray V ARIABLE -S IZE C OLLECTION filled part unfilled part current size maximum size

25 V ARIABLE -S IZE C OLLECTION public class { … final static int A_MAX_SIZE = 50; String[] a = new String[A_MAX_SIZE]; int aSize = 0; … //process a for (int index = 0; index < aSize; index++) System.out.println(a[index]); … final int B_MAX_SIZE = 50; String[] b = new String[B_MAX_SIZE]; int bSize = 0; … //process b … }

26 S PECIAL T YPE public class {... AVariableSizeCollection a = new AVariableSizeCollection();... for ( int index = 0; index < a.size; index++) System.out.println(a.contents[index]); … AVariableSizeCollection b = new AVariableSizeCollection();... } public class AVariableSizeCollection { public static final int MAX_SIZE = 50; public String[] contents = new String [MAX_SIZE]; public int size = 0; } No Encapsulation Size Not Updated a.contents[a.size] = Console.readString();

27 S UPPORTING E NCAPSULATION public interface …. { public static final int MAX_SIZE = 50; public void addElement(String element); public void print(); } User-specificImplementation-specific

28 H ISTORY public interface StringHistory { public void addElement(String element); public int size(); public String elementAt( int index); }

29 I MPLEMENTING A H ISTORY public class AStringHistory implements StringHistory { public final int MAX_SIZE = 50; String[] contents = new String[MAX_SIZE]; int size = 0; public int size() { return size;} public String elementAt ( int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(String element) { if (isFull()) System.out.println("Adding item to a full history"); else { contents[size] = element; size++; }

30 U SING A H ISTORY public static void main(String[] args) { StringHistory names = new AStringHistory(); while ( true ) { String input = Console.readString(); if (input.length() > 0) if (input.charAt(0) == 'q') break ; else if (input.charAt(0) == 'p' ) print(names); else names.addElement(input); } Exits from the loop

31 P RINTING A H ISTORY static void print(StringHistory strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.size(); elementNum++) System.out.println(strings.elementAt(elementNum)); System.out.println("******************"); }

32 AP OINT H ISTORY Variable-sized Collection History Elements accessed by ObjectEditor Conventions for exporting elements

33 C ONVENTIONS FOR V ARIABLE -S IZED C OLLECTION public interface PointHistory { public void addElement ( int x, int y); public Point elementAt ( int index); public int size(); } Read Methods Write Method Arbitrary Type

34

35 E XTRA S LIDES

36 loans null loans null ALoan(10000) AnotherLoan(100) Loan[]Loan