Review of Previous Lesson

Slides:



Advertisements
Similar presentations
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Road Map Introduction to object oriented programming. Classes
Java Unit 9: Arrays Declaring and Processing Arrays.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CSC 212 Object-Oriented Programming and Java Part 2.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter VII: Arrays.
Chapter 1.2 Introduction to C++ Programming
The need for Programming Languages
Chapter 1.2 Introduction to C++ Programming
Data Types Variables are used in programs to store items of data e.g a name, a high score, an exam mark. The data stored in a variable is entered from.
Class Structure 15-Jun-18.
Introduction to Computer Science / Procedural – 67130
Lecture 5: Some more Java!
Yanal Alahmad Java Workshop Yanal Alahmad
Multiple variables can be created in one declaration
Variables and Primative Types
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Yong Choi School of Business CSU, Bakersfield
slides created by Ethan Apter
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
Object Oriented Programming
Defining methods and more arrays
slides created by Ethan Apter
Algorithm Correctness
If selection construct
int [] scores = new int [10];
elementary programming
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Building Java Programs
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Review of Previous Lesson
Functions continued.
Programming Logic and Design Fifth Edition, Comprehensive
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming Language
Review of Previous Lesson
Data Structures & Algorithms
Review of Previous Lesson
Review of Previous Lesson
Review of Previous Lesson
Classes, Objects and Methods
Review of Previous Lesson
Just Enough Java 17-May-19.
Review of Previous Lesson
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Review of Previous Lesson
LCC 6310 Computation as an Expressive Medium
slides created by Ethan Apter and Marty Stepp
Review of Previous Lesson
Review of Previous Lesson
Review for Midterm 3.
Classes and Objects Object Creation
Java Coding 6 David Davenport Computer Eng. Dept.,
Arrays.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Review of Previous Lesson 26/05/2019 Review of Previous Lesson State as many Vocabulary words and Learning Objectives that you remember from the last lesson as you can. Remember to grade yourself from 0 - 3.

Object Orientated Programming Paradigm (OOP) 26/05/2019 Object Orientated Programming Paradigm (OOP) Own Classes - Exercises “Has-a” = Objects that Contain Objects, final

Language Features and other Testable Topics 26/05/2019 Tested in the AP CS A Exam Notes Not tested in the AP CS A Exam, but potentially relevant/useful Variables private instance variables: visibility (private), final Methods 9 public static void main(String[] args), command line arguments, Miscellaneous OOP “has-a” relationships,

Language Features and other Testable Topics 26/05/2019 Notes: 9. The main method and command-line arguments are not included in the subset. In free-response questions, students are not expected to invoke programs. In the AP Computer Science Labs, program invocation with main may occur, but the main method will be kept very simple.

26/05/2019 Write your own programs: Write your own programs from “scratch”. Of course you should use previous programs for reference, but write your code from “scratch” (do not copy and paste).

Trees What smaller objects does this simple tree model consist of? 26/05/2019 Trees What smaller objects does this simple tree model consist of? Could an object of type Tree contain a instance variable that points to a Cone?

“Has-a” = Objects that Contain Objects 26/05/2019 “Has-a” = Objects that Contain Objects As with real world objects, software objects are often composed of smaller software objects. Instance variables can also be reference variables. Object composition is sometimes called a “has-a” relationship between objects. In the real world objects can be directly part/embedded in other objects. However, in the software world, objects only have references/pointers to the objects (and primitive types) within them.

Can an object contain instance variables that point to other objects? 26/05/2019 Can an object contain instance variables that point to other objects? Yes: e.g. private Cone branches; private Cylinder trunk; It may feel like the Cone and Cylinder objects are directly part of the Tree object (a complete Cone object and complete Cylinder object are embedded in the Tree object). But in Java, a tree consists of a pointer to the branches and a pointer to a trunk (and some int variables). How many objects are there? 3: Tree object Cone object Cylinder object ?

Ways to declare & assign a reference variable 26/05/2019 Some constructors may require certain information called “actual” parameters written inside the brackets in a specific order separated by ,. null/nothing ClassName refVarName = new ClassName ( ); // This is the typical way you have mainly used until now. Declares a reference variable & the class of the object. Constructs a new object and a reference to that object is put in the variable. Sometimes parameters are needed when the object is constructed. ClassName refVarName; …. refVariableName = new ClassName( ) ; Declares a reference variable & the class of the object it will later refer to but no object is created. ClassName refVarNameOne, variableNameTwo, …; Declares multiple reference variables, potentially referring to objects of the same class but no objects are created. ClassName refVarNameOne = new ClassName ( ), variableNameTwo = new ClassName ( ) ; Declares multiple reference variables, constructs new objects and their references are assigned to the variables.

Trees A simple tree consists of a cone and a cylinder. 26/05/2019 Trees A simple tree consists of a cone and a cylinder. You should use the Cone & Cylinder classes written previously. A Tree has-a Cone A Tree has-a Cylinder An object of type Tree will contain instance variables that point to a Cone & a Cylinder. All you need is a cone for the branches and a cylinder for the trunk. We will also use x, y, & z for the location of a tree. The volume of the tree is the sum of the cone volume and the cylinder volume: volume(). The area: - area(): (Cone area + Cylinder area) – (2*area of the circle at the top of the Cylinder) The area of the circle at the top of the cylinder and its intersection with the base of the cone are not part of the solid's area. Continued on the next slide.

Trees Write a Tree class. 26/05/2019 As well as what has been discussed on the previous slide also include: A toString() method to display the position of the tree and the instance variables of the cone & cylinder. grow(double rate) Trees can grow at a certain rate (e.g. 0.10) which affects all dimensions. getter methods for x, y & z. Continued on the next slide.

Trees Answer in your comments: 26/05/2019 How many objects are there if are 2 Tree objects? Explain. Why is it sensible not to have setter methods of x, y & z of a tree?

Trees Answer in your comments: 26/05/2019 How many objects are there if are 2 Tree objects? Explain. 6: 2 trees 2 cylinders (1 for each tree) 2 cones (1 for each tree) Why is it sensible not to have setter methods of x, y & z of a tree? Because trees do not naturally move!

Trees 26/05/2019 Also write a Forest class that: Constructs at least 4 Tree objects tree0, tree1, tree2, … . Has a default constructor. Has a setTree() method that accepts a Tree reference & an integer that says which instance variable to set and assigns it a corresponding reference variable e.g. if (treeNum == 0) tree0 = tree; if (treeNum == 1) tree1 = tree; Has a getTree() method that returns a specified tree. Has a toString() method which returns all trees created in one String variable e.g. String str = ""; if ( tree0 != null ) str += "Tree 0: " + tree0 + "\n"; Has area() and volume() methods. Write a separate class with a main() to demonstrate all methods.

Forest Answer in your comments: 26/05/2019 How many objects in a forest of 4 trees? Explain. Object instance variables are initialised by default to what? What does this mean? When and why can we just write tree0 when we really mean tree0.toString (see example below)? e.g. str += "Tree 0: " + tree0 + "\n";

Forest Answer in your comments: 26/05/2019 16 How many objects in a forest of 4 trees? Explain. 13: 1 forest 4 trees 4 cones 4 cylinders Object instance variables are initialised by default to what? What does this mean? Object instance variables are initialised by default to null. When a reference contains null it is not pointing to any object. When and why can we just write tree0 when we really mean tree0.toString? The toString() method is automatically called when an object is treated as a String (e.g. in expressions that result in a String or printing them to the console). 16

26/05/2019 Weather Report Write a program to keep track of weather for your city by recording the high temperature of each day for a month. Write a Month class that can construct an object that: Represents one month of weather. Records the high temperature for each day of the month. Has methods to access and change data. Has methods that summarize the data. In a month of up to 31 days there will be up to 31 values to store. What do you propose could be done to store all this data? Continued on the next slide.

26/05/2019 Weather Report In a month of up to 31 days there will be up to 31 values to store so this is a good place for an array. As we only need to store one temperature per day, you should store these temperatures in an array of ints. If we needed to store multiple measurements (temperature & pressure for every hour of the day in a day) we would use a Day class that represents each day and have an array of Days in each Month. Continued on the next slide.

Weather Report A Month might not have valid data for every day. 26/05/2019 A Month might not have valid data for every day. Some days might be in the future, and other days might have been missed. You will deal with this by using an array named valid, which will contain a true/false value for each day to indicate if the temperature for that day is valid. When initially constructed, each cell of an array is initialized to a default value. The array temp[] will be filled with zeros, but these are not actual data for the days. The role of the array valid[] is to show which days have valid data. e.g. If (say) valid[5] is true, then the corresponding temperature for day 5 is valid. Boolean arrays are automatically initialised to false, so just after construction no days have valid data. Instance variables: int month; // 1 == January int year; // year as an int, eg 2017 int daysInMonth; // number of days in this month 2 arrays (temp & valid) final int ERRORFLAG = 999; // See later slides for details. Continued on the next slide.

? Weather Report A parametrised constructor 26/05/2019 The temperature for each day will be added after the Month object has been built. The constructor only needs to know the year and month number so it set month, year & daysInMonth but it will only create the temp & valid arrays (not populate them). How can we declare an array on one line and create an array on another? What do you think the size of the arrays should be? dataType[] arrayName; // Establishes the fact that intArray is an int array variable but no array actually exists yet, only a reference to the array is created. arrayName = new dataType[arraySize]; // Creates an array. ? Continued on the next slide.

Weather Report A parametrised constructor 26/05/2019 Each array will have a length of 32 to make the use of the array more convenient to (index 1 for day 1, array index 2 for day 2, and so on). This means that the 0 cell in each array will not be used. This is a common programming trick which may seem like a waste as, in addition to wasted 0 cell, not all months have 31 days, but a few unused bytes in modern computers is not an issue. The instance variable daysInMonth contains the number of days in a particular month. The constructor will need to computes this based on the year and month supplied as parameters. Use a series of if statements and a isLeapYear() method to compute this. See later for details on how to write a isLeapYear() method. Continued on the next slide.

26/05/2019 final The reserved word final tells the compiler that the value will not change. e.g. final datatype thisVariableWillNotChange = …. The names of constants (variables declared as final) can follow the same rules as the names for variables or use only capital letters.

Weather Report constants 26/05/2019 /* Will be used as a return value by some methods to flag an error. The caller will be expected to check the return value before using it. Using the same variable name throughout a program’s code will improve readability and consistency. See next slide for more details.*/ final int ERRORFLAG = 999;

Weather Report - Methods: 26/05/2019 isLeapYear( int year ) return ((year%4==0) && (year%100!=0)) || (year%400==0); getTemp(int dayNumber) Error check for a dayNumber being out of range and return ERRORFLAG if so. setTemp(int dayNumber, int temp) Error check for dayNumber being out of range and return True if dayNumber is valid and False if it is not. https://en.wikipedia.org/wiki/Leap_year#Gregorian_calendar Note that to use this feature effectively main() should check if setTemp returns False and act accordingly: if ( !jan.setTemp(day, highestTemp ) ) /* This still calls .setTemp on jan & checks if it returns false but is a more professional, neater & elegant way to write if … = False. */ System.out.println("error in input"); /* Also note that jan.setTemp(day, highestTemp ) on its own will also compile and execute but as the return value is never examined or stored anywhere it will just be unused & lost. */ Continued on the next slide.

Weather Report - Methods: 26/05/2019 Weather Report - Methods: toString() To return the month/year, all days & valid temperatures as one string (with / & line breaks as appropriate) for display. e.g. countValidDays() Count the number of days with valid data. avgTemp() Compute the average temperatures for all valid days. Return ERRORFLAG if count < 0 (& main() should produce a suitable error message). Use an String Escape Sequence for line breaks. For reminder see “nested for” (slide 9). For reminders on how to store primitive data types in String variables see “Strings” (slide 71 or earlier if necessary). Continued on the next slide.

26/05/2019 Weather Report Write a Year class to keep track of the high temperature for each day for a year. Each Year object will be composed of 12 Month objects in an array Months[]. It is convenient to number months starting at one, so the array would be 13 cells long, but cell 0 would not be used. This is different from the array in Month objects where each cell of the array is a primitive type. Optional extension: You may create your own suitable methods for the Year class. Write a separate class with main() to demonstrate the use of both classes and any methods of each. Continued on the next slide.

Weather Report Answer the following questions in your comments: 26/05/2019 Weather Report Answer the following questions in your comments: Is an array an object? What value are arrays of boolean initialized to? Why is this important in relation to the valid array? What does final mean in Java? What happens to a Month object when the program finishes? What are reference variables automatically initialized to?

Weather Report Answer the following questions in your comments: 26/05/2019 Answer the following questions in your comments: Is an array an object? Yes. What value are arrays of boolean initialized to? Why is this important in relation to the valid array? Boolean arrays are automatically initialized to false. So just after construction no days have valid data. What does final mean in Java? final is used for named constants. What happens to a Month object when the program finishes? It vanishes. What are reference variables automatically initialized to? null The array month starts out with 13 cells, each containing the special value null.

StringArray Write a StringArray class with a main() method. 26/05/2019 Declare and construct an array ‘strArray’ to keep track of 8 strings. You may or may not use cell 0 (your choice). Write a loop to ask the user for strings to populate strArray but allow the user to exit the loop at any time by entering a exit code of your choice. i.e. It is possible that some or all cells will be null. Write a loop to display each cell of the array. cell … strArray[…] Make sure to avoid printing null cells. Continued on the next slide.

StringArray Answer the following questions in your comments: 26/05/2019 StringArray Answer the following questions in your comments: What does this statement do? String str; Must all of the Strings pointed to by cells of the array be of the same length? Why might strArray[j].length() not always work? Explain what happens if the following statements occur in this order in a program? strArray[0] = “Hello”; strArray[0] = “Good-bye”;

StringArray Answer the following questions in your comments: 26/05/2019 Answer the following questions in your comments: What does this statement do? String str; It declares a variable str that can hold a reference to a String object. No object has been created. Must all of the Strings pointed to by cells of the array be of the same length? No. Each element of the array is of the same type a reference to a String, but the Strings themselves can be of different lengths. Why might strArray[j].length() not always work? No. Sometimes strArray[j] is null, so strArray[j].length() will not work. Explain what happens if the following statements occur in this order in a program? strArray[0] = “Hello”; strArray[0] = “Good-bye”; This will replace the reference in cell 0 with a reference to a new String, containing the characters "Good-bye" .

String[] args 26/05/2019 Finally, after all this time, we will look at this! (But note that AP CS does not require it.) The phrase String[] args says that main() has a parameter which is a reference to an array of String references. This array is constructed by the Java system just before main() gets control. The elements of the array refer to Strings that contain text from the command line that starts the program. Write a StringDemo class that anticipates the creation of a String array named args and attempts to print out the contents. for (int j=0; j < args.length; j++ ) System.out.println( "Parameter " + j + ": " + args[j] ); Now try starting the program with command line arguments. e.g. java StringDemo stringA stringB string java StringDemo 123 0045.7 java StringDemo 23 87 13 67 -42 How can a program tell how many command line arguments it has been given? Comment on this.

26/05/2019 String[] args How can a program tell how many command line arguments it has been given? Use args.length

5/26/2019 Grade yourself Grade yourself on the vocabulary and learning objectives of the presentation.