Download Oct 20 - Computer Science

Document related concepts
no text concepts found
Transcript
COMP 110
Review for midterm exam
Luv Kohli
October 20, 2008
MWF 2-2:50 pm
Sitterson 014
Announcements

Midterm on Wednesday, October 22
◦ Closed everything, except open mind

Extra office hours in my office (Sitterson Hall 280)
◦ Tuesday, 3pm-5pm
◦ Wednesday, 11am-12pm

Wednesday 3pm-4pm office hours canceled for this
week

Brooks Building dedication this Friday, October 24
◦ Lots of neat demos all day
2
Questions?
3
Today in COMP 110

A whirlwind tour of almost everything we
have covered so far
◦ These slides are essentially extracted from
earlier lectures

Go over Lab 5
4
Hardware vs. Software

Hardware - physical machine
◦ CPU, Memory

Software - programs that give instructions
to the computer
◦ Windows XP, Games, jGRASP
5
Hardware
CPU – the “brain” of your computer
 Memory – stores data for the computer

◦ How much the “brain” can remember
◦ Main memory
◦ Auxiliary memory
6
Memory
Measured in bytes
 1 byte = 8 bits
 Bit is either 0 or 1
 Language of the computer is in bits

7
Programming Languages
Your Program
High-level language
(human readable)
Compiler
Machine Language (Bits)
Low-level language
(computer readable)
8
Algorithms and pseudocode

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
9
Variables
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!

10
How to use variables

Declare a variable
◦ int number;

Assign a value to the variable
◦ number = 37;

Change the value of the variable
◦ number = 513;
11
Keywords
Reserved words with predefined
meanings
 You cannot name your variables keywords
 if, else, return, new

12
Type
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, UpgradedSmiley
13
Assignment Statements
Change a variable’s value
 Syntax:

◦ variable = expression;

Example:
◦ sleepNeeded = 8;
◦ sleepDesired = sleepNeeded * 2;
14
Assignment compatibilities
int x = 5;
double y = 12.7;
y = x;

=
x = y;

=
OK
Not OK
15
Type casting
x = (int) y;

= (int)
OK
16
Arithmetic Operators

Unary operators
◦ +, -, ++, --, !

Binary arithmetic operators
◦ *, /, %, +,  rate*rate + delta
 1/(time + 3*mass)
 (a - 7)/(t + 9*v)
17
Modular Arithmetic - %
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)

18
Parentheses and Precedence

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
19
Errors
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

20
Strings

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
21
String
String animal = “aardvark”;
System.out.println(animal);
aardvark
22
String Concatenation
String animal = “aardvark”;
String sentence;
sentence = “My favorite animal is the ” + animal;
My favorite animal is the aardvark
23
Strings methods
myString.length();
 myString.equals(“a string”);
 myString.toLowerCase();
 myString.trim();


Many others
24
String Indices
U N C
0 1 2
3
i
4
s
5
6
G
7
r
8
e a t
9 10 11
String output = myString.substring(1, 8);
25
String Indices
U N C
0 1 2
3
i
4
s
5
6
G
7
r
8
e a t
9 10 11
String output = myString.substring(1, 8);
26
Escape Characters
\”
\’
\\
\n
\r
\t
Double quote
Single quote
Backslash
New line
Carriage return
Tab
27
Keyboard Input
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
28
28
Comments
// this is a comment
/* This is also
a comment */
29
Boolean Expressions
An expression that is either true or false
 Examples:

◦ It is sunny today (true)
◦ 10 is larger than 5 (true)
◦ Today is Saturday (false)
30
if/else statements
import java.util.*;
Prompt
user for
integer
Yes
Print:
“big
number”
Is input
greater
than 10?
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();
No
Print:
“small
number”
if (inputInt > 10)
{
System.out.println("big number");
}
else
{
System.out.println("small number");
}
}
}
31
Java Comparison Operators
==
!=
>
>=
<
<=
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
32
boolean type

Can be either true or false
boolean sunny = true;
boolean cloudy = false;
if (sunny || cloudy)
{
// walk to school
}
33
&&, || operators

AND
if ((temperature > 50) && (temperature < 75))
{
// walk to school
}

OR
if (sunny || cloudy)
{
// walk to school
}
34
The ! (NOT) operator
!true is false
 !false is true
 Example: walk to school if it is NOT cloudy

if (!cloudy)
{
// walk to school
}
35
switch statement
switch(year)
{
Controlling expression
case 1:
System.out.println(“freshman”);
break;
case 2:
System.out.println(“sophomore”);
Case labels
break;
case 3:
Break statements
System.out.println(“junior”);
break;
case 4:
System.out.println(“senior”);
break;
default:
System.out.println(“unknown”);
break;
}
Default case:
all other values
36
Loops

Loop: part of a program that
repeats
Start


Body: statements being
repeated
Iteration: each repetition of
body
Enough
sandwiches?
Make
sandwich
Yes
No
Distribute
sandwiches

Stopping condition
37
Types of Loops

while
◦ Safest choice
◦ Not always most elegant

do-while
◦ Loop iterates AT LEAST once

for
◦ Similar to while, but often more convenient
syntax
38
Using a while loop
n=1
int n = 1;
while (n <= 10)
{
System.out.println(n);
n = n + 1;
}
n <= 10?
Yes
No
Output n
End
n=n+1
39
Using a do-while loop
int n = 1;
do
{
System.out.println(n);
n = n + 1;
} while (n <= 10);
Don’t forget
the semicolon!
40
Using a for loop
int n;
for (n = 1; n <= 10; n++)
{
System.out.println(n);
}
41
Infinite loop example
int n;
for (n = 1; n <= 10; n = 0)
{
System.out.println(n);
}
42
The break statement
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);
43
Identify the loop body from pseudocode
Output instructions to the user
Initialize variables
Prompt user for input
Read a number into variable next
sum = sum + next;
Repeated statements
become your loop body
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
Statements that are only done once
are not part of your loop body
44
Initializing statements
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.
45
Ending a loop

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
46
Nested loops example: friendly greetings
for (int stdLineA = 1; stdLineA <= 3; stdLineA++)
{
for (int stdLineB = 4; stdLineB <= 6; stdLineB++)
{
System.out.println(“Student ” + stdLineA +
“ shakes Student ” + stdLineB +
“’s hand.”);
}
}
Inner loop
Outer loop
47
Classes, Objects, and Methods
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
48
Class

A class is the definition of a kind of object
◦ A blueprint for constructing specific objects
Class Name: Automobile
Data:
amount of fuel
speed
license plate
Methods (actions):
accelerate:
How: Press on gas pedal.
decelerate:
How: Press on brake pedal.
49
Objects, Instantiation
Object Name: patsCar
Object Name: suesCar
amount of fuel: 10 gallons
speed: 55 miles per hour
license plate: “135 XJK”
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
50
Objects
Important: classes do not have data;
individual objects have data
 Classes specify what kind of data objects
have

51
Creating an object
Create an object jack of class Student
Student jack = new Student();
Assign memory
address of object to
variable
Return memory
address of object
Create an object
by calling a
constructor
Scanner keyboard = new Scanner(System.in);
Create an object keyboard of class Scanner
52
Instance variables

Data defined in the class are called
instance variables
public
public
public
public
String name;
int classYear;
double GPA;
String major;
public: no restrictions on
how these instance
variables are used (more
details later – public is
actually a bad idea here)
variables
type: int, double, String…
53
Methods

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()
54
Methods
returns a String
public String getMajor()
{
return major;
}
return type
returns nothing
public void increaseYear()
{
classYear++;
}
55
Calling methods that return nothing
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);
56
Methods that return a value
public String getClassYear()
{
if (classYear == 1)
return “Freshman”;
else if (classYear == 2)
return “Sophomore”;
else if ...
}
57
Calling methods that return a value
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);
58
Instance variables vs. local variables
public class Student
{
public String name;
public int classYear;
// ...
• classYear and name are
instance variables
• can be used in any method in
this class
public void printInfo()
{
String info = name + “: ” + classYear;
System.out.println(info);
}
public void increaseYear()
{
classYear++;
}
• info is a local variable declared
inside method printInfo()
• can only be used inside method
printInfo()
public void decreaseYear()
{
classYear--;
}
}
59
Instance variables vs. local variables
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”;
}
public void decreaseYear()
{
classYear--;
}
}
// ERROR!!!
The compiler will not recognize
the variable info inside of method
increaseYear()
60
Methods with parameters

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;
}
Parameters go inside
parentheses of method
header
61
Methods with multiple parameters

Multiple parameters separated by
commas
public double getTotal(double price, double tax)
{
return price + price * tax;
}
62
Method parameters and arguments

Order, type, and number of arguments
must match parameters specified in
method heading

Add these two numbers
+
= ???
63
Calling a method with parameters
public class Student
{
public String name;
public int classYear;
// ...
public void setName(String studentName)
{
name = studentName;
}
public void setClassYear(int year)
{
classYear = year;
}
}
64
Calling a method with parameters
public static void main(String[] args)
{
Student jack = new Student();
jack.setName(“Jack Smith”);
jack.setClassYear(3);
}
Arguments
65
Calling methods from methods

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();
66
Various things
Information hiding
 Encapsulation

67
public/private modifier
public void setMajor()
 public int classYear;


public: there is no restriction on how you
can use the method or instance variable
68
public/private modifier
private void setMajor()
 private int classYear;


private: can not directly use the method
or instance variable’s name outside the
class
69
Example
public class Student
{
public int classYear;
private String major;
}
Student jack = new Student();
OK, classYear is public
jack.classYear = 1;
jack.major = “Computer Science”;
Error!!! major is private
70
Accessors and mutators
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
71
Well encapsulated
Imagine a wall between interface and implementation
Implementation:
Interface:
Private instance variables
Private constants
Private methods
Bodies of public methods
Comments
Headings of public methods
Public named constants
Programmer
who uses the
class
72
Variables of a primitive type

When declaring a variable, a certain
amount of memory is assigned based on
the declared primitive type
int age;
double length;
char letter;
memory

What goes in this memory?
73
Variables of a primitive type

A data value is stored in the location
assigned to a variable of a primitive type
74
Variables of a class type

What goes in these variables?
Student jack;
String inputString;
memory
75
Variables of a class type

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

76
== vs. equals() for Strings explained
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!

77
== vs. equals() for Strings explained

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

78
Writing the .equals() method
public class Book
{
private String name;
private int page;
public boolean equals(Book book)
{
return (this.name.equals(book.name) &&
this.page == book.page);
}
}
79
Parameters of a primitive type
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
80
Parameters of a class type
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
81
Parameters of a class type
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!
82
Lab 5
If you intended to come to the extra
session last Tuesday, but were unable to
due to another commitment, send me an
email
 Lab 5 solution will be posted on web site
by tonight

83
Wednesday

Midterm exam
84