CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Similar documents
CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

public Student(int theage, String thename, char thegrade) { age = theage; name = thename; grade = thegrade; } public int getage() { return age;}

Chapter 4 Defining Classes I

Java is an objet-oriented programming language providing features that support

Introduction to Programming Using Java (98-388)

EECS168 Exam 3 Review

Principles of Object Oriented Programming. Lecture 4

CONDITIONAL EXECUTION

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

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

SSE3052: Embedded Systems Practice

Assignment 1 due Monday at 11:59pm

Classes Classes 2 / 35

CS171:Introduction to Computer Science II

The Java language has a wide variety of modifiers, including the following:

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

University of Massachusetts Amherst, Electrical and Computer Engineering

Designing data types. Fundamentals of Computer Science I

Java Object Oriented Design. CSC207 Fall 2014

Abstract class & Interface

Methods and Data (Savitch, Chapter 5)

CS 231 Data Structures and Algorithms, Fall 2016

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CS 251 Intermediate Programming Methods and Classes

Utilities (Part 2) Implementing static features

Instance Method Development Demo

CMP 326 Midterm Fall 2015

CMSC 202H. Classes and Objects: Reusing Classes with Composition

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

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

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

The Basic Parts of Java

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Tutorial 12. Exercise 1: Exercise 2: CSC111 Computer Programming I

Java Classes, Inheritance, and Interfaces

Chapter 6 Introduction to Defining Classes

CS 2334: Programming Structures and Abstractions: Exam 1 October 3, 2016

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

TeenCoder : Java Programming (ISBN )

Classes Classes 2 / 36

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CS 251 Intermediate Programming Methods and More

CompuScholar, Inc. 9th - 12th grades

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Anatomy of a Class Encapsulation Anatomy of a Method

Chapter 4: Writing Classes

Object Oriented Programming with Java

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

More Java Basics. class Vector { Object[] myarray;... //insert x in the array void insert(object x) {...} Then we can use Vector to hold any objects.

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

CS1083 Week 2: Arrays, ArrayList

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Questions Answer Key Questions Answer Key Questions Answer Key

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Informatik II (D-ITET) Tutorial 6

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.

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Defining Classes and Methods

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Building Java Programs

Last Name: Circle One: OCW Non-OCW

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Object-Oriented Programming

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

Objects as a programming concept

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Software and Programming 1

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

ECE 122. Engineering Problem Solving with Java

Distributed Systems Recitation 1. Tamim Jabban

CO Java SE 8: Fundamentals

COP 3330 Final Exam Review

The high-level language has a series of primitive (builtin) types that we use to signify what s in the memory

CIS 110: Introduction to Computer Programming

Outline. CIS 110: Introduction to Computer Programming. Any questions? My life story. A horrible incident. The awful truth

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

MIDTERM REVIEW. midterminformation.htm

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

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

More on variables and methods

CSIS 10B Lab 2 Bags and Stacks

Chapter 6 Lab Classes and Objects

Media Computation. Lecture 15.2, December 3, 2008 Steve Harrison

CS313D: ADVANCED PROGRAMMING LANGUAGE

Use the scantron sheet to enter the answer to questions (pages 1-6)

Transcription:

CSCI 136 Data Structures & Advanced Programming Lecture 3 Fall 2017 Instructors: Bill & Bill

Administrative Details Lab today in TCL 216 (217a is available, too) Lab is due by 11pm Sunday Copy your folder to Dropoff folder for your lab (see handout) Lab 1 design doc is due at beginning of lab Written design docs will be required at all labs You ll discuss with another student at start of lab Several implementation options Some may be better than others... 2

CoinStrip Design How to store game state? Space needs Time to find coin Useful methods? void makemove(whichcoin, howfar) boolean legalmove(whichcoin, howfar) tostring()? What, if anything, did lab description omit? Form of game board to show players 3

Last Time Arrays, Operators, Expressions Some Simple Examples (Sum0-5) Entering, editing, compiling, running programs 4

Today s Outline Control structures Branching: if else, switch, break, continue Looping: while, do while, for, for each Object oriented programming Basics (OOP) Strings and String methods More on Class Types Interface specification for behavior abstraction Inheritance (class extension) for code reuse Abstract Classes 5

Control Structures Select next statement to execute based on value of a boolean expression. Two flavors: Looping structures: while, do/while, for Repeatedly execute same statement (block) Branching structures: if, if/else, switch Select one of several possible statements (blocks) Special: break/continue: exit a looping structure break: exits loop completely continue: proceeds to next iteration of loop 6

while & do-while Consider this code to flip coin until heads up... Random rng = new Random(); int flip = rng.nextint(2), count = 0; while (flip == 0) { } count++; flip = rng.nextint(2);...and compare it to this int flip, count = 0; do { count++; flip = rng.nextint(2); } while (flip == 0) ; // count flips until heads // count flips until heads 7

For & for-each Here s a typical for loop example int[] grades = { 100, 78, 92, 87, 89, 90 }; int sum = 0; for( int i = 0; i < grades.length; i++ ) sum += grades[i]; This for construct is equivalent to int i = 0; while ( i < grades.length ) { sum += grades[i]; i++; } Can also write for ( int g : grades ) // called for-each construct sum += g; 8

Loop Construct Notes The body of a while loop may not ever be executed The body of a do while loop always executes at least once For loops are typically used when number of iterations desired is known in advance. E.g. Execute loop exactly 100 times Execute loop for each element of an array The for-each construct is often used to access array (and other collection type) values when no updating of the array is required We ll explore this construct more later in the course 9

If/else if (x > 0) // Exactly 1 "if" clause y = 1 / x; else if (x < 0) { // 0 or more "else if" clauses x = - x; y = 1 / x; } else // at most 1 "else" clause System.out.println( Can t divide by 0! ); The single statement can be replaced by a block: any sequence of statements enclosed in {} 10

switch Example: Encode clubs, diamonds, hearts, spades as 0, 1, 2, 3 int x = mycard.getsuit(); // a fictional method switch (x) { } case 1: case 2: System.out.println("Your card is red"); break; case 0: case 3: System.out.println("Your card is black"); break; default: System.out.println("Illegal suit code!"); break; 11

Break & Continue Suppose we have a method isprime to test primality Find first prime > 100 for(int i = 101; ; i++ ) // What s with ; ;? if ( isprime(i) ) { System.out.println( i ); break; } Print primes < 100 for(int i = 1; i < 100; i++) { if (!isprime(i)) continue; System.out.println(i); } 12

Summary Basic Java elements so far Primitive and array types Variable declaration and assignment Operators & operator precedence Expressions Control structures Branching: if else, switch, break, continue Looping: while, do while, for, for each Edit (emacs), compile (javac), run (java) cycle 13

Object-Oriented Programming Objects are building blocks of Java software Programs are collections of objects Cooperate to complete tasks Represent state of the program Communicate by sending messages to each other Through method invocation 14

Object-Oriented Programming Objects can model: Physical items - Dice, board, dictionary Concepts - Date, time, words, relationships Processing - Sort, search, simulate Objects contain: State (instance variables) Attributes, relationships to other objects, components Letter value, grid of letters, number of words Functionality (methods) Accessor and mutator methods addword, lookupword, removeword 15

Object Support in Java Java supports the creation of programmerdefined types called class types A class declaration defines data components and functionality of a type of object Data components: instance variable (field) declarations Functionality: method declarations Constructor(s): special method(s) describing the steps needed to create an object (instance) of this class type 16

A Simple Class Premise: Define a type that stores information about a student: name, age, and a single grade. Declare a Java class called Student with data components (fields/instance variables) String name; int age; char grade; And methods for accessing/modifying fields Getters: getname, getage, getgrade Setters: setage, setgrade Declare a constructor, also called Student 17

public class Student { // instance variables private int age; private String name; private char grade; // A constructor public Student(int theage, String thename, char thegrade) { age = theage; name = thename; grade = thegrade; } // Methods for accessing/modifying objects //...see next slide... 18

public int getage() {return age;} public String getname() {return name;} public char getgrade() {return grade;} public void setage(int theage) { } age = theage; public void setgrade(char thegrade) { grade = thegrade; } } // end of class declaration 19

Testing the Student Class public class TestStudent { } public static void main(string[] args) { Student a = new Student(18, Bill J", 'A'); Student b = new Student(21, Bill L", 'A+'); // Nice printing System.out.println(a.getName() + ", " + a.getage() + ", " + a.getgrade()); System.out.println(b.getName() + ", " + b.getage() + ", " + b.getgrade()); // Tacky printing System.out.println(a); System.out.println(b); } 20

Worth Noting We can create as many student objects as we need, including arrays of Students Student[] class = new Student[3]; class[0] = new Student(18, Huey", 'A'); class[1] = new Student(20, Dewey", 'B'); class[2] = new Student(20, Louie", 'A'); Fields are private: only accessible in Student class Methods are public: accessible to other classes Some methods return values, others do not public String getname(); public void setage(int theage); 21

A Programming Principle Use constructors to initialize the state of an object, nothing more. State: instance variables Frequently they are short, simple methods More complex constructors will typically use helper methods. You constructors can call other constructors to reuse code 22

Access Modifiers public and private are called access modifiers They control access of other classes to instance variables and methods of a given class public : Accessible to all other classes private : Accessible only to the class declaring it There are two other levels of access that we ll see later Data-Hiding (encapsulation) Principle Make instance variables private Use public methods to access/modify object data 23

More Gotchas public class Student { // instance variables private int age; private String name; private char grade; // A constructor public Student(int age, String name, char grade) { // What would age, name, grade // refer to here...? } 24

Use this public class Student { // instance variables private int age; private String name; private char grade; // A constructor public Student(int age, String name, char grade) { this.age = age; this.name = name; this.grade = grade; } 25

String in Java Is a Class Type Java provides language support for Strings String literals: Bob was here!, -11.3, A, If a class provides a method with signature public String tostring() Java will automatically use that method to produce a String representation of an object of that class type. For example System.out.println(aStudent); would use the tostring method of Student to produce a String to pass to the println method Pro Tip: Always provide a tostring method! It helps to debug if you can visualize the state of your objects! 26

String methods in Java Useful methods (also check String javadoc page) indexof(string) : int indexof(string, startindex) : int substring(frompos, topos) : String substring(frompos) : String charat(int index) : char equals(other) : bool ß Always use this! tolowercase() : String touppercase() : String compareto(string) : bool length() : int startswith(string) : bool Understand special cases! 27