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