Catie Welsh March 4, 2011.  Midterm on Monday, March 14th ◦ Closed books, no notes, no computer  No office hours during Spring Break ◦ However, I will.

Slides:



Advertisements
Similar presentations
Catie Welsh March 2,  Program 3 due tonight by 11:59pm  Lab 5 due Friday by 1pm  Sample Midterm is posted on course website ◦ Solutions will.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Classes, Objects, and Methods.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CMT Programming Software Applications
Classes, Objects, and Methods
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 110 Primitive Types, Strings, and Console I/O Tabitha Peck M.S. January 23, 2008 MWF 3-3:50 pm Philips
COMP 110 Branching Statements and Boolean Expressions Tabitha Peck M.S. January 28, 2008 MWF 3-3:50 pm Philips
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Introduction to C Programming
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
COMP Classes Yi Hong May 22, Announcement  Lab 2 & 3 due today.
COMP More About Classes Yi Hong May 22, 2015.
Introduction to Information and Computer Science Computer Programming Lecture c This material (Comp4_Unit5c), was developed by Oregon Health and Science.
Catie Welsh January 12, 2011 MWF 1-1:50 pm Sitterson
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Bryce Canyon, Utah CSE 114 – Computer Science I Objects and Reference.
COMP Mid-Term Review Yi Hong May 27, 2015.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
CPS120: Introduction to Computer Science Decision Making in Programs.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
COMP 110 switch statements and while loops Luv Kohli September 10, 2008 MWF 2-2:50 pm Sitterson
Introduction to Java Java Translation Program Structure
COMP Flow of Control: Branching 1 Yi Hong May 19, 2015.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
COMP 110 Objects and references Luv Kohli October 8, 2008 MWF 2-2:50 pm Sitterson 014.
CSC 212 Object-Oriented Programming and Java Part 2.
February 28, 2013 COMP Introduction to Programming Objects and References Haohan Li TR 11:00 – 12:15, SN 011 Spring 2013.
COMP 110 Worksheet review, debugger Luv Kohli September 29, 2008 MWF 2-2:50 pm Sitterson 014.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
COMP 110 Classes Luv Kohli October 1, 2008 MWF 2-2:50 pm Sitterson 014.
Catie Welsh February 2,  Program 1 Due Today by 11:59pm today  Program 2 Assigned Today  Lab 2 Due Friday by 1:00pm 2.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Catie Welsh February 23,  Lab 4 due on Friday  Lab 5 will be assigned on Friday 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
COMP 110 Branching Statements and Boolean Expressions Luv Kohli September 8, 2008 MWF 2-2:50 pm Sitterson
Catie Welsh January 31,  Project 1 Due Wednesday  Lab 1 Grades are posted 2.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
COMP 110 More about classes Luv Kohli October 3, 2008 MWF 2-2:50 pm Sitterson 014.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Eastside Robotics Alliance / Newport Robotics Group 1 T/Th, 6:30 – 8:30 PM Big Picture School Day 3 · 10/9/2014.
Information and Computer Sciences University of Hawaii, Manoa
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 21, 2011
Lecture 5: Some more Java!
Yanal Alahmad Java Workshop Yanal Alahmad
COMP Objects and References
COMP 110 Review for midterm exam
Chapter 5: Control Structures II
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
COMP 110 Information hiding and encapsulation
Introduction to C++ Programming
Announcements Program 2 is due tomorrow by noon Lab 4 was due today
Chapter 2 Programming Basics.
Primitive Types and Expressions
Announcements Assignment 2 and Lab 4 due Wednesday.
Announcements Lab 5 due Wednesday at noon.
Presentation transcript:

Catie Welsh March 4, 2011

 Midterm on Monday, March 14th ◦ Closed books, no notes, no computer  No office hours during Spring Break ◦ However, I will be around, so me if you have questions or want to meet 2

3

 Go over Program 3  A whirlwind tour of almost everything we have covered so far ◦ These slides are essentially extracted from earlier lectures 4

5

 Hardware - physical machine ◦ CPU, Memory  Software - programs that give instructions to the computer ◦ Windows XP, Games, Eclipse 6

 CPU – the “brain” of your computer  Memory – stores data for the computer ◦ How much the “brain” can remember ◦ Main memory ◦ Auxiliary memory 7

 Measured in bytes  1 byte = 8 bits  Bit is either 0 or 1  Language of the computer is in bits 8

9 Your Program Compiler Machine Language (Bits) High-level language (human readable) Low-level language (computer readable)

 Algorithm – a set of instructions for solving a problem  Pseudocode – combination of code and English used to express an algorithm before writing algorithm into code 10

 Used to store data in a program  The data currently in a variable is its value  Name of variable is an identifier  Can change value throughout program  Choose variable names that are meaningful! 11

 Declare a variable ◦int number;  Assign a value to the variable ◦number = 37;  Change the value of the variable ◦number = 513; 12

 Reserved words with predefined meanings  You cannot name your variables keywords  if, else, return, new 13

 What kind of value the variable can hold  Two kinds of types. ◦ Primitive type - indecomposable values  Names begin with lowercase letters  int, double, char, float, byte, boolean, some others ◦ Class type - objects with both data and methods  Names by convention begin with uppercase letter  Scanner, String, Student 14

 Change a variable’s value  Syntax: ◦ variable = expression;  Example: ◦ sleepNeeded = 8; ◦ sleepDesired = sleepNeeded * 2; 15

int x = 5; double y = 12.7; y = x;  = x = y;  = 16 OK Not OK

x = (int) y;  = 17 (int) OK

 Unary operators ◦ +, -, ++, --, !  Binary arithmetic operators ◦ *, /, %, +, -  rate*rate + delta  1/(time + 3*mass)  (a - 7)/(t + 9*v) 18

 Remainder  7 % 3 = 1 (7 / 3 = 2, remainder 1)  8 % 3 = 2 (8 / 3 = 2, remainder 2)  9 % 3 = 0 (9 / 3 = 3, remainder 0) 19

 Expressions inside parentheses evaluated first ◦(cost + tax) * discount ◦cost + (tax * discount)  Highest precedence First: the unary operators: +, -, ++, --, ! Second: the binary arithmetic operators: *, /, % Third: the binary arithmetic operators: +, - Lowest precedence 20

 Syntax error – grammatical mistake in your program  Run-time error – an error that is detected during program execution  Logic error – a mistake in a program caused by the underlying algorithm 21

 A string (lowercase) is a sequence of characters ◦ “Hello world!” ◦ “Enter a whole number from 1 to 99.”  String (capital S) is a class in Java, not a primitive type 22

String animal = “aardvark”; System.out.println(animal); aardvark 23

String animal = “aardvark”; String sentence; sentence = “My favorite animal is the ” + animal; My favorite animal is the aardvark 24

 myString.length();  myString.equals(“a string”);  myString.toLowerCase();  myString.trim();  Many others 25

26 UNCisGreat String output = myString.substring(1, 8);

27 UNCisGreat String output = myString.substring(1, 8);

28 \”Double quote \’Single quote \\Backslash \nNew line \rCarriage return \tTab

Scanner kb = new Scanner(System.in); int num = kb.nextInt(); 29

// this is a comment /* This is also a comment */ 30

 An expression that is either true or false  Examples: ◦ It is sunny today (true) ◦ 10 is larger than 5 (true) ◦ Today is Saturday (false) 31

32 Is input greater than 10? Yes No Prompt user for integer Print: “big number ” Print: “small number ” import java.util.*; public class FlowChart { public static void main(String[] args) { System.out.println("Give me an integer:"); Scanner keyboard = new Scanner(System.in); int inputInt = keyboard.nextInt(); if (inputInt > 10) { System.out.println("big number"); } else { System.out.println("small number"); } } }

33 == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Example expressions: variable <= 6 myInt > 5 5 == 3

 Can be either true or false boolean sunny = true; boolean cloudy = false; if (sunny || cloudy) { // walk to school } 34

 AND if ((temperature > 50) && (temperature < 75)) { // walk to school }  OR if (sunny || cloudy) { // walk to school } 35

 !true is false  !false is true  Example: walk to school if it is NOT cloudy if (!cloudy) { // walk to school } 36

switch(year) { case 1: System.out.println(“freshman”); break; case 2: System.out.println(“sophomore”); break; case 3: System.out.println(“junior”); break; case 4: System.out.println(“senior”); break; default: System.out.println(“unknown”); break; } 37 Controlling expression Case labels Break statements Default case: all other values

 Loop: part of a program that repeats  Body: statements being repeated  Iteration: each repetition of body  Stopping condition 38 Start Enough sandwiches ? Distribute sandwiches No Yes Make sandwich

 while ◦ Safest choice ◦ Not always most elegant  do-while ◦ Loop iterates AT LEAST once  for ◦ Similar to while, but often more convenient syntax ◦ Most useful when you have a known # of iterations you need to do 39

int n = 1; while (n <= 10) { System.out.println(n); n = n + 1; } 40

int n = 1; do { System.out.println(n); n = n + 1; } while (n <= 10); 41 Don’t forget the semicolon!

int n; for (n = 1; n <= 10; n++) { System.out.println(n); } 42

int n; for (n = 1; n <= 10; n = 0) { System.out.println(n); } 43

for (int item = 1; item <= 5; item++) { System.out.print(“Enter cost of item #” + item + “: $”); amount = keyboard.nextDouble(); total = total + amount; if (total >= 100) { System.out.println(“You spent all your money.”); break; } System.out.println(“Your total so far is $” + total); } System.out.println(“You spent $” + total); 44

Output instructions to the user Initialize variables Prompt user for input Read a number into variable next sum = sum + next; Prompt user for input Read a number into variable next sum = sum + next; Prompt user for input Read a number into variable next sum = sum + next;... Output the sum 45 Repeated statements become your loop body Statements that are only done once are not part of your loop body

 Variables used in your loop need to be initialized (set to a value) before the loop  next ◦Read a number into variable next ◦ We read a new value for next before using it during each iteration of the loop so we do not need to initialize it  sum ◦sum = sum + next; ◦sum is on the right side of an assignment statement. sum MUST have a valid value before the loop starts. 46

 Count-controlled loops ◦ If you know the number of loop iterations ◦ for (count = 0; count < iterations; count++)  User-controlled loops ◦ Ask-before-iterating ◦ Sentinel value 47

for (int stdLineA = 1; stdLineA <= 3; stdLineA++) { for (int stdLineB = 4; stdLineB <= 6; stdLineB++) { System.out.println(“Student ” + stdLineA + “ shakes Student ” + stdLineB + “’s hand.”); } 48 Inner loop Outer loop

 Class: a definition of a kind of object  Object: an instance of a class ◦ Contains instance variables (data) and methods  Methods ◦ Methods that return a value ◦ Methods that return nothing 49

 A class is the definition of a kind of object ◦ A blueprint for constructing specific objects 50 Class Name: Automobile Data: amount of fuel speed license plate Methods (actions): accelerate: How: Press on gas pedal. decelerate: How: Press on brake pedal.

51 Object Name: patsCar amount of fuel: 10 gallons speed: 55 miles per hour license plate: “135 XJK” Object Name: suesCar amount of fuel: 14 gallons speed: 0 miles per hour license plate: “SUES CAR” Object Name: ronsCar amount of fuel: 2 gallons speed: 75 miles per hour license plate: “351 WLF” Instantiations, or instances, of the class Automobile

 Important: classes do not have data; individual objects have data  Classes specify what kind of data objects have 52

Create an object jack of class Student Student jack = new Student(); Scanner keyboard = new Scanner(System.in); Create an object keyboard of class Scanner 53 Create an object by calling a constructor Return memory address of object Assign memory address of object to variable

 Data defined in the class are called instance variables public String name; public int classYear; public double GPA; public String major; 54 public: no restrictions on how these instance variables are used (more details later – public is actually a bad idea here) type: int, double, String… variables

 Two kinds of methods ◦ Methods that return a value  Examples: String’s.substring() method, String’s.indexOf() method, etc. ◦ Methods that return nothing  Example: System.out.println() 55

public String getMajor() { return major; } public void increaseYear() { classYear++; } 56 returns a String returns nothing return type

 object, followed by dot, then method name, then ()  Use them as Java statements Student jack = new Student(); jack.classYear = 1; jack.increaseYear(); System.out.println(“Jack’s class year is ” + jack.classYear); 57

public String getClassYear() { if (classYear == 1) return “Freshman”; else if (classYear == 2) return “Sophomore”; else if... } 58

 object, followed by dot, then method name, then () (same as before)  Use them as a value of the type specified by the method’s return type Student jack = new Student(); jack.major = “Computer Science”; String m = jack.getMajor(); System.out.println(“Jack’s full name is ” + jack.getName()); System.out.println(“Jack’s major is ” + m); 59

public class Student { public String name; public int classYear; //... public void printInfo() { String info = name + “: ” + classYear; System.out.println(info); } public void increaseYear() { classYear++; } public void decreaseYear() { classYear--; } 60 classYear and name are instance variables can be used in any method in this class info is a local variable declared inside method printInfo() can only be used inside method printInfo()

public class Student { public String name; public int classYear; //... public void printInfo() { String info = name + “: ” + classYear; System.out.println(info); } public void increaseYear() { classYear++; info = “My info string”; // ERROR!!! } public void decreaseYear() { classYear--; } 61 The compiler will not recognize the variable info inside of method increaseYear()

 Parameters are used to hold the value that you pass to the method  Parameters can be used as (local) variables inside the method public int square(int number) { return number * number; } 62 Parameters go inside parentheses of method header

 Multiple parameters separated by commas public double getTotal(double price, double tax) { return price + price * tax; } 63

 Order, type, and number of arguments must match parameters specified in method heading  Add these two numbers 64 += ???

public class Student { public String name; public int classYear; //... public void setName(String studentName) { name = studentName; } public void setClassYear(int year) { classYear = year; } 65

public static void main(String[] args) { Student jack = new Student(); jack.setName(“Jack Smith”); jack.setClassYear(3); } 66 Arguments

 A method body can call another method ◦ Done the same way: receiving_object.method();  If calling a method in the same class, do not need receiving_object: ◦method();  Alternatively, use the this keyword ◦this.method(); 67

 Information hiding  Encapsulation 68

 public void setMajor()  public int classYear;  public: there is no restriction on how you can use the method or instance variable 69

 private void setMajor()  private int classYear;  private: can not directly use the method or instance variable’s name outside the class 70

public class Student { public int classYear; private String major; } Student jack = new Student(); jack.classYear = 1; jack.major = “Computer Science”; 71 OK, classYear is public Error!!! major is private

 How do you access private instance variables?  Accessor methods (a.k.a. get methods, getters) ◦ Allow you to look at data in private instance variables  Mutator methods (a.k.a. set methods, setters) ◦ Allow you to change data in private instance variables 72

73 Programmer Implementation: Private instance variables Private constants Private Methods Bodies of all methods Method definitions Interface: Comments Headings of public methods Public defined constants Interface: Comments Headings of public methods Public defined constants

 When declaring a variable, a certain amount of memory is assigned based on the declared primitive type  What goes in this memory? 74 int age ; double length ; char letter ; memory

 A data value is stored in the location assigned to a variable of a primitive type 75

 What goes in these variables? 76 Student jack ; String inputString ; memory

 Contain the memory address of the object named by the variable ◦ NOT the object itself  What is an address?  Object is stored in some other location in memory  The address to this other location is called a reference to the object  Class types are also called reference types 77

 String is a class type  What happens when you have String s1 = new String(“Hello”); String s2 = new String(“Hello”); boolean strEqual = (s1 == s2);  strEqual is false! Why?  s1 and s2 store different addresses! 78

 What happens when you have String s1 = new String(“Hello”); String s2 = new String(“Hello”); boolean strEqual = (s1.equals(s2));  strEqual is true! Why?  String’s.equals() method checks if all the characters in the two Strings are the same 79

public class Book { private String name; private int page; public boolean equals(Book book) { return (this.name.equals(book.name) && this.page == book.page); } 80

public void increaseNum(int num) { num++; } public void doStuff() { int x = 5; increaseNum(x); System.out.println(x); }  Prints 5. Why?  num is local to increaseNum method; does not change x 81

public void changeBook(Book book) { book = new Book(“Biology”); } public void doStuff() { Book jacksBook = new Book(“Java”); changeBook(jacksBook); System.out.println(jacksBook.getName()); }  Prints Java. Why?  book is local to changeBook, does not change jacksBook 82

public void changeBook(Book book) { book.setName(“Biology”); } public void doStuff() { Book jacksBook = new Book(“Java”); changeBook(jacksBook); System.out.println(jacksBook.getName()); }  Prints Biology. Why?  book contains the same address as jacksBook! 83

 Solution will be posted later or tomorrow, depending on when everyone gets it turned in 84

 Midterm exam 85