Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 110: Spring 20091 Announcements Lab 0 was due today (noon) Lab 1 is on Friday Bring laptops New students see me after class.

Similar presentations


Presentation on theme: "COMP 110: Spring 20091 Announcements Lab 0 was due today (noon) Lab 1 is on Friday Bring laptops New students see me after class."— Presentation transcript:

1 COMP 110: Spring 20091 Announcements Lab 0 was due today (noon) Lab 1 is on Friday Bring laptops New students see me after class

2 COMP 110: Spring 20092 Today in COMP 110 Objects and Classes Review Algorithms and pseudocode Variables & Operations Programming Demo Vending Machine Change

3 COMP 110: Spring 20093 Object-Oriented Programming What are objects? Entities that can represent real-world things or abstractions E.g. cars, houses, books, System.out Objects are concrete instances of Classes Car is a class, myCar is an Object of type Car Objects perform or have actions performed on them car.start() plane.fly() book.turnPage()

4 COMP 110: Spring 20094 Object-Oriented Programming What is object-oriented programming? Programming methodology where programs are composed of a collection of objects that can act alone or interact with one another Example A race car simulation program might have car, driver, racetrack, and onlooker objects A driver might ‘drive’ a car object An onlooker object might ‘cheer’ a driver object

5 COMP 110: Spring 20095 Object Attributes Classes have general attributes, objects have specific attributes Car class attributes vs. specific object attributes Model : “Scion” Year : 2006 Owner : “John Hansen” Location : “Parking Lot” An individual attribute is referred to as a variable or field; the set of an object’s attributes is called its state

6 COMP 110: Spring 20096 Object Actions Objects perform actions, or have actions performed on them. These are generally called methods Sometimes called functions or procedures Example A car object might allow the following actions Accelerate Brake Start

7 COMP 110: Spring 20097 Object Actions Performing actions on a object can change its state Example If we sell a car, we change its owner If we accelerate the car, we will change its location

8 COMP 110: Spring 20098 Classes A Class describes a general template for creating a certain kind of object Example We have two car objects One is a 2000 Toyota Camry owned by John Doe A second is a 2001 Ford Focus owned by Samantha Smart While the two car objects are different, they are both types of cars and have the same type of attributes Both cars are thus members of the Class Car

9 COMP 110: Spring 20099 Classes and Objects Class Car Make Model Year Owner Location Focus object Make = Ford Model = Focus Year = 2001 Owner = Samantha Smart Location = School Camry object Make = Toyota Model = Camry Year = 2000 Owner = John Doe Location = Garage

10 COMP 110: Spring 200910 Creating a car object Class Car Make Model Year Owner Person john = new Person(“John Hansen”); Car myScion= new Car(); myScion.setMake(“Toyota”); myScion.setModel(“Camry”); myScion.setYear(2006); myScion.setOwner(john); scion object Make = Toyota Model = Scion xB Year = 2006 Owner = John Hansen

11 COMP 110: Spring 200911 Questions on Classes or Objects?

12 COMP 110: Spring 200912 Algorithms What is an algorithm? A set of instructions for solving a problem

13 COMP 110: Spring 200913 Algorithm Example How to make a peanut butter and jelly sandwich? Get two slices of bread Get some peanut butter Get some jelly Get a knife Spread peanut butter on the first slice of bread Spread jelly on the second slice of bread Put the two slices of bread together

14 COMP 110: Spring 200914 Pseudocode Combination of code and English used to express an algorithm before writing the algorithm into code useful in planning out programs before you actually write them

15 COMP 110: Spring 200915 Algorithm Example 2 How to compute the total cost of all the groceries in your shopping cart? Simple, just start with the number 0 and add the cost of each item one by one. Let’s look at how we might describe this in pseudocode

16 COMP 110: Spring 200916 Algorithm Example 2 Computing the total cost of groceries in pseudocode total = 0 for each item in the cart total = total + (cost of that item) At the end of the algorithm, “total” is the total cost of all items in the cart

17 COMP 110: Spring 200917 Variables Used to store data in a program Think of it is a container for a value Example myVariable = 6; Set the value of “myVariable” to 6 Can change value throughout program myVariable = 8; The value of “myVariable” is now 8

18 COMP 110: Spring 200918 Variables Name of a variable is called its identifier Choose variable names that are meaningful! Example a = a + b; No one will know what these variables mean accntBalance = accntBalance + deposit; Is much better

19 COMP 110: Spring 200919 How to use Variables Declare a variable Assign a value to the variable Change the value of the variable

20 COMP 110: Spring 200920 Variable Declarations Tells the computer what type of data the variable will hold Allocates space in memory for the data Examples: int count, score, myInt; char letter; double totalCost, ratio;

21 COMP 110: Spring 200921 Syntax Set of grammatical rules in a language Simple syntax for English sentences Subject Verb Object. E.g “I won the game.” Syntax for variable declarations in Java: Type Variable_1, Variable_2, …; Examples: int count, score, myInt; char letter; double totalCost, ratio;

22 COMP 110: Spring 200922 Variables and Memory A variable corresponds to a location in memory variable n1 Use this cell to store the value of n1 Prevent this cell from being used by other variables later main memory

23 COMP 110: Spring 200923 Type What kind of value the variable can hold Two kinds of types Primitive type - indecomposable values (single number or letter) int, double, char, boolean Class type - objects with both data and methods Scanner, System

24 COMP 110: Spring 200924 Four Kinds of Primitive Types Integer types byte, short, int, long Represent whole numbers such as 0, 5, 1883443 Floating-point types float, double Represent numbers with some fractional component such as 1.01, 3932.123532, 0.0 Character char Represents a single character such as ‘A’, ‘;’, ‘8’ Boolean boolean Represents a single bit (on or off, true or false, 1 or 0)

25 COMP 110: Spring 200925 Java Primitive Types Type Name Kind of Value Memory Used Range of Values byteInteger1 byte-128 to 127 shortInteger2 bytes-32,768 to 32,768 intInteger4 bytes-2,147,483,648 to 2,147,483,647 longInteger8 bytes-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 floatFloating-point4 bytes±3.40282347 x 10 +38 to ±1.40239846 x 10 -45 doubleFloating-point8 bytes±1.79769313486231570 x 10 308 to ±4.94065645841246544 x 10 -324 charCharacter2 bytes0 to 65,535 boolean 1 bitTrue of False (0 to 1)

26 COMP 110: Spring 200926 Java Primitive Types: Range

27 COMP 110: Spring 200927 Variables and Memory When declaring a variable, a certain amount of memory is assigned based on the declared primitive type int age ; double length ; char letter ; main memory

28 COMP 110: Spring 200928 Variable Declaration Why is it important to tell the computer the type of the data? Different types of data take up different amounts of space in memory Different types of data may allow different operations We can add two numbers, but does it make sense to add two letters?

29 COMP 110: Spring 200929 Variable Declarations For now, declare all your variables inside main public class ExampleProgram { public static void main(String[] args) { int count; double average; … }

30 COMP 110: Spring 200930 How to Name Variables Use a combination of Letters, digits (0-9), underscore (_) First character cannot be a digit Java is case sensitive “myVariable” & “myvariable” are considered different identifiers

31 COMP 110: Spring 200931 Example Variable Names Legal names inputStream, my_Grade, my_Grade2 Illegal names Bright*, Power-Hour, 7eleven Generally first word is lowercase, following words start uppercase: myCat, numStudents, newYorkCity

32 COMP 110: Spring 200932 Variable Names Exercise Name weezer michael.bolton ben_folds n1n kenny-G 311 2pac Legal? Yes No Yes No

33 COMP 110: Spring 200933 Keywords Reserved words with predefined meanings if, else, return, new, … see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/ _keywords.html You cannot use a keyword as a variable name int if; will not compile int ifThen; Is ok

34 COMP 110: Spring 200934 Assignment Statements Change a variable’s value Syntax: variable = expression; Example: hoursPerDay= 24; hoursPerWeek= hoursPerDay*7; ‘=’ sign is called the assignment operator

35 COMP 110: Spring 200935 Behind the Assignment Statement variable = expression; CPU calculates the value of the expression Writes the value to the memory location of the variable hoursPerWeek= hoursPerDay* 7; Get the current value of hoursPerDay from its memory location Calculate hoursPerDay* 7 Assign the result to the memory location of hoursPerWeek

36 COMP 110: Spring 200936 Assignment Statement A variable can occur on both sides of an assignment statement Example count = count + 10; increases variable count by 10

37 COMP 110: Spring 200937 Variable Initialization You need to give variables an initial value before you use them Otherwise you may observe unexpected behavior int count; //variable declaration count = 1; //variable assignment

38 COMP 110: Spring 200938 Variable Initialization You can also initialize variables directly in the declaration For example int myVar; //this is a declaration myVar = 0; //this is an assignment Is equivalent to int myVar = 0; //declaration AND assignment

39 COMP 110: Spring 200939 Variable Initialization Multiple variables can be declared and initialized simultaneously int grade0 = 95, grade1 = 89, grade2 = 71;

40 COMP 110: Spring 200940 Arithmetic Operators The usual suspects Addition (+) a + b Subtraction (-) a - b Multiplication (*) a * b Division (/) a / b NOTE: (9/2) = 4 and (9.0/2) = 4.5

41 COMP 110: Spring 200941 Remainder Operator The remainder or modulo operator (%) gives the remainder when one whole number is divided by another Example i = 10%4; //the value of i will be 2 j = 6%3; //the value of j will be 0 k = 17%6; //the value of k will be 5

42 COMP 110: Spring 200942 Remainder Operator The remainder operator can be used to determine if a number is even or odd Given any integer n, n%2 will produce either 0 or 1 If n%2 equals 0, n is even If n%2 equals 1, n is odd

43 COMP 110: Spring 200943 Parentheses and Precedence Parentheses can be used to indicate the order in which operations should be performed Example What is the value of “result”? int a = 3, b = 1, c = 2, result = 0; result = (a + b) * c; result = a + (b * c); result = 8 result = 5

44 COMP 110: Spring 200944 Review You should now Have a better understanding of objects and classes Have a good idea of what an algorithm is Be able to write a basic Java program that performs simple arithmetic

45 COMP 110: Spring 200945 Testing & Debugging It’s easy to make mistakes when programming These mistakes are called bugs The process of eliminating mistakes in a program is called debugging

46 COMP 110: Spring 200946 Programming Errors Syntax Error – Failure to follow the rules of the language E.g. missing semi-colon Run-time Error – An error that causes the program to halt and produce an error message E.g. Program crashes Logic Error – When a program fails to produce the correct result E.g accidentally using addition when you meant to use subtraction Hardest to locate!

47 COMP 110: Spring 200947 Vending Machine Change Problem Given an amount of change in cents, determine the number of quarters, dimes, nickels, and pennies that equals that amount of change Example: 67 cents would be dispensed as 2 quarters, 1 dimes, 1 nickel, and 2 pennies

48 COMP 110: Spring 200948 Programming Demo Vending Machine Change Steps Pseudocode Programming Testing/Debugging

49 COMP 110: Spring 200949 Designing the Algorithm How do we know that 67 cents is 2 quarters, 1 dimes, 1 nickel and 2 pennies? First we used as many quarters as we could (2) That leaves 17 cents Second we used as many dimes as we could (1) Still left with 7 cents Third we used as many nickels as we could (1) That leaves 2 cents Lastly we used the remaining amount as pennies (2)

50 COMP 110: Spring 200950 Vending Machine Change Pseudocode Ask user for the amount of change Determine the amount in quarters Subtract the value in quarters from amount Determine the amount in dimes Subtract the value in dimes from amount Determine the amount in nickels Subtract the amount in nickels from amount Set the number of pennies to the remaining amount Output the result

51 COMP 110: Spring 200951 Friday Recitation Lab 1 Bring Laptops (fully charged) New students see me after class


Download ppt "COMP 110: Spring 20091 Announcements Lab 0 was due today (noon) Lab 1 is on Friday Bring laptops New students see me after class."

Similar presentations


Ads by Google