Robots. Byron Weber Becker. chapter 6

Similar documents
Robots. Byron Weber Becker. chapter 6

TaxiBot New attributes Variables Math! TaxiBot

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

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS111: PROGRAMMING LANGUAGE II

More on variables and methods

Lecture 11. Instructor: Craig Duckett. Instance Variables

Chapter 4: Writing Classes

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

CS111: PROGRAMMING LANGUAGE II

Java Review. Fundamentals of Computer Science

COMP 202 Java in one week

Lecture 6. Instructor: Craig Duckett

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

Simple Java Programming Constructs 4

Course Outline. Introduction to java

CS112 Lecture: Working with Numbers

Anatomy of a Class Encapsulation Anatomy of a Method

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

I. Variables and Data Type week 3

Instructor: Craig Duckett

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

Today s Agenda. Quick Review

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

CS1083 Week 2: Arrays, ArrayList

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Building Java Programs

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

CIS 110: Introduction to Computer Programming

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

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Building Java Programs

ASSIGNMENT 4 Classes and Objects

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

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

CT 229 Java Syntax Continued

CSCI 161 Introduction to Computer Science

ECE 122. Engineering Problem Solving with Java

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

Asking For Help. BIT 115: Introduction To Programming 1

Object-Oriented Programming

BIT 115: Introduction To Programming LECTURE 3. Instructor: Craig Duckett

13 th Windsor Regional Secondary School Computer Programming Competition

EECS168 Exam 3 Review

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

BCIS 3630 Dr. GUYNES SPRING 2018 TUESDAY SECTION [JAN version] GRADER COURSE WEBSITE

AP Computer Science Summer Work Mrs. Kaelin

Programming Exercise 7: Static Methods

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Bjarne Stroustrup. creator of C++

Object Oriented Programming. Java-Lecture 1

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling)

Combo Lecture Lecture 14/15. Instructor: Craig Duckett

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS 106 Introduction to Computer Science I

Assignment 1 due Monday at 11:59pm

Lecture 12. Instructor: Craig Duckett

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Object Oriented Programming. Week 1 Part 1 An introduction to Java, Objects and JUnit

CS1004: Intro to CS in Java, Spring 2005

Data Types and the while Statement

UNDERSTANDING CLASS DEFINITIONS CITS1001

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Lecture 3 Tao Wang 1

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Lecture 7. Instructor: Craig Duckett OUTPUT

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring 2010

Week 6: Review. Java is Case Sensitive

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

ECE 122. Engineering Problem Solving with Java

Building Java Programs

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

CS 231 Data Structures and Algorithms, Fall 2016

APCS Semester #1 Final Exam Practice Problems

Introduction to Programming Using Java (98-388)

Variables and Operators 2/20/01 Lecture #

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Lecture 2: Operations and Data Types

Com S 227 Spring 2018 Topics and review problems for Exam 1 Monday, February 19, 6:45 pm Exam locations by last name:

CS 1302 Chapter 9 (Review) Object & Classes

CS 106A, Lecture 5 Booleans and Control Flow

Reviewing all Topics this term

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Methods and Data (Savitch, Chapter 5)

DATA AND ABSTRACTION. Today you will learn : How to work with variables How to break a program down Good program design

Introduction to JAVA

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Introduction to Java Applications

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Transcription:

Using Variables Robots Learning to Program with Java Byron Weber Becker chapter 6

Announcements (Oct 3) Reminder: Reading for today y( (Oct 3 rd ) Ch 6.1-6.4 Reading for Wednesday (Oct 3 rd ) The rest of Ch 6 Reminder: program#4 is due next Monday Pair programming? Lab quiz is scheduled for tomorrow Be on time! You will NOT be allowed to use textbook or online resources. you can get help from Eclipse though..

Lab Quiz#1 Using a non-robot class Create using the best constructor Make calls to getters Make calls to commands that Update data Update and print data Print data

Arithmetic There are 5 arithmetic operators in Java: + - addition --subtraction * - multiplication / - division % - modulus

Precedence Multiplication, division, and modulus have higher precedence that addition and subtraction. Always work left to right. This is no different from what you learned in grade school.

Integer Division Dividing two integers results in an Dividing two integers results in an integer ALWAYS.

Practice Give the value of int variable ans 1. ans = 5 / 3; 2. ans = 5%3 3; 3. ans = (3 / 2) * 2; 4. ans = 3 / 4; 5. ans = 17 % 4; 6. ans = 14 10 / 2 + 8;

Practice Give the value of int variable ans 7. ans = (14 10) / 2 + 8; 8. ans = 14 10 / (2 + 8); 9. ans = 4 / 7; 10.ans = 12 % 2; 11.ans = 25 % 7; 12.ans = 7 / 2;

Practice Give the value of double variable val 13.val = 7 / 2; 14.val = 7.0 / 2; 15.val = 3 + 1 / 2.0; 16.val = 3 / 2 * 2.0;

Review: arithmetic and logical Arithmetic operators * / + - operators Logical/boolean operators && : AND : OR! : NOT (..)

Review: operators

Writing to the Console Text interface. System.out is an object that is provided to enable us to show data to the user. Two main methods: System.out.print( stuff t t( t to print ); System.out.println( stuff to print ); Can pass in any kind of thing to print

Review: Switch Statements Can replace certain cascading if statements Each if must test the same condition The test value must be integer or single character Uses a break statement to end execution May have a default case

Review: Switch on Integer switch(num) { case 1: tax = price *.01; break; case 2: tax = price *.0725; break; bea default: tax = 0; } Value

Review: Switch on Character switch(code) { case 'D': tax = price *.01; break; case 'R': R: tax = price *.0725; break; bea default: tax = 0; } Value

Review: Cascading Switch switch(count) { case 5: System.out.println("5"); case 4: System.out.println("4"); case 3: System.out.println( println("3"); case 2: System.out.println("2"); case 1: System.out.println("1"); default: System.out.println("Blast Off!!"); }

Review: Make a Row of 10 int count = 10; while(count > 0) { } Things this.putthing(); this.move(); count--;

For-Loops A for-loop combines the declaration, initialization, and incrementing/decrementing of the counter in the loop condition This is the one place I will allow you to Use a temp variable that is declared on the fly Use a single letter variable name

Pattern for FOR loop for(«initialize»;«test»;«increment») { } «statements to repeat» braces surround the statements to repeat and are even with for the statements to repeat are indented uniformly

Make a Row of 10 Things for(int i=10; i > 0; i--) { } this.putthing(); tthi this.move();

Another For-Loop Example Method to be added to a child of City public void makevertwall(int topst, int topav, int length, Direction direction) { for(int i=topst; i < topst+length; i++) { new Wall(this, i, topav, direction); } }

What is the final value of total? int total=5; int num=10; for(int i=0; i<num; i++) { } total = total * num;

WHILE-TRUE Loops DO NOT USE THESE!!! These loops are rarely correctly used by new programmers There are certain circumstances when a while-true loop can be correctly used We will not write ANY programs where a while-true loop is necessary

A Few Words About Expressions Never include == true or == false when using predicates Use simple statements Use positively stated expressions when possible Avoid using! Create predicates as helper methods for clarity

Practice Write a method that uses a for loop to add Write a method that uses a for loop to add the numbers 1 to 10 and returns the result.

MorePractice Write a method to compute the sum of all integers between first and second (including first and second), where first and second are integers and first is less than or equal to second. The method should return the sum. You may not change the value of either first or second.

Still More Practice Write a method to find the smaller of two integers. The method will accept two integers and return the smaller of the two. If they are the same, then the method returns either one of them.

One More Practice Telephone company rules to calculate the cost of a long distance call are as follows. If the call is over 60 minutes, the cost is 7 cents per minute. If the call is over 20 minutes long, the cost is 10 cents per minute. If the call is 20 minutes or less, the cost is 13 cents per minute. Write a method that t takes the length of a call in minutes and returns the per minute rate for that call.

Practice Switch Statements Write a method to determine the purchaser s discount based on a code. If the code is 7, the discount is 10%. If the code is 3, the discount is 15%. If the code is 12, the discount is 4%. If the code is 1, there is no discount. If the code is 8, the discount is 30%. The method should return the discount.

Chapter Objectives Extend an existing class with new instance variables Store calculation results in temporary variables Write methods using parameter variables Use constants to write more understandable code Understand the difference between Instance variables Temporary or Local variables Parameter variables Constants

Instance Variables (Class Data) Attributes or data pertaining to a class object Different for each instance of the class Always private or protected never public Scope the life of the object Accessibility Visible within class methods Hidden outside of class

Temporary/Local Variables Used to hold data for short time within a Used to hold data for short time within a method Calculation results Temporary copy of instance data Counters User input etc Scope the life of the method Accessibility Visible within this method only

Parameter Variables Data passed into a method Declaration done in the method header Names not associated with calling statement Scope the life of the method Accessibility Visible within this method only

Constants public static final int SIZE = 50; Names written in ALL_CAPS_WITH_UNDERSCORES Must be initialized when declared Typically declared as public Always visible within class or outside Declared as static stored once in memory and shared by all instances of class Accessed using class name not instance of class Declared as final Value cannot be changed by program

Instance Data in Robot Classes Consider the class data of the Robot class int street int avenue Direction direction ThingBag backpack No new data was added to RobotSE

Adding Instance Variables to Child Class Consider a child of RobotSE called Consider a child of RobotSE called HomingBot that can remember where it starts and return there when told to gohome Add instance variables to hold starting street, avenue, and direction Write the constructor so it stores this data How will gohome vary from the goto method in the GoBot from lab 6?

From GoBot in Lab 6 public void goto(int st, int ave) { this.facestreet(st); this.gotostreet(st); this.faceave(ave); this.gotoave(ave); } Assuming each method had been properly coded to work in GoBot how will they change in our HomingBot?

LimitedCarryBot Create as child of HomingBot Can only carry a limited number of Things Hold this as additional instance variable Set using a parameter passed to the constructor Override pickthing so if the robot tries to pick up too many things it will spin around twice, then drop everything on that spot A method called exercise will make the robot return home (presumably to exercise) and increase the number of Things the robot is able to carry by one

The Keyword final Values declared as final become constant their value cannot be changed They should always be declared using ALL_CAPS They must be given a value when declared Suppose we always want our HomingBot to face east after returning home what changes would we make in the class?

The Keyword static Since every instance of a class will have the same constant(s) and since those constants will always have the same value we only need to store that value once for all instances of the class Constants are typically declared as static and made public Only created once in memory Accessible from anywhere without out an instance of the class Accessed using the class name

Static used in a Class for Variables and Constants t Static class data (either variable or constant) is created once when the first instance is created and is accessible by all instances of the class Thus every instance of a class has the ability to change the value of static variables Used very sparingly If declared as public you can access the value using the class name double tax = Part.SALES_TAX;

Static used in a Class for methods Static methods cannot be dependent on any class data that is not also static Static methods are called using the class name NOT an instance of the class The Math class has all static methods and constants Never create a Math object Call all methods using Math.methodName() Access all constants using Math.CONSTANT

Accessor Methods Also called getters Used to access (get) values stored in instance data Always non-void return type Rarely has parameter values You won t always provide an accessor for every data element

Mutator Methods Also called setters Used to mutate (change or set) values stored in instance data Always void return type Typically has a single parameter value the value we will be storing You won t always provide a mutator for You won t always provide a mutator for every data element

Using System.out System is a special class used for standard input and output (I/O) The System class contains several useful class fields and methods It cannot be instantiated out is a PrintStream class field within the System class All PrintStream methods are available using System.out.methodName();

Common PrintStream Methods println is used to print a string of data (passed as the parameter) with a line return at the end print is used to print a string of data without a line return at the end Multiple calls to print can be used to print information one after the other on the same line println() can be used to get a simple line return without printing data