COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson...

53
COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014

Transcript of COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson...

Page 1: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110:Introduction to Programming

Tyler JohnsonJanuary 28, 2009

MWF 11:00AM-12:15PMSitterson 014

Page 2: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20092

Announcements

Lab 1 due tomorrow by midnight

TA Office Hours (SN 043)Nick Dragan - Tues/Thurs 2-3pm• [email protected]

Georgi Tsankov – Tues 4-6pm• [email protected]

Page 3: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20093

Questions?

Page 4: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20094

Today in COMP 110

Documentation and Style

Branching

Page 5: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20095

Documentation & Style

The programs you write should be correct

They should also be easy to read and understand

Page 6: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20096

Variable Names

Part of creating good programs is choosing meaningful variable names

If a variable stores a count, call it “count”, if a variable represents a cost, call it “cost”

Page 7: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20097

Variable Names

Variables are typically named using only numbers and digits

int count;int grade1, grade2;

Underscores are generally avoided in variable names

Page 8: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20098

Capitalization in Variable Names

Variable and object names are generally written in lower case

double cost, ratio;

Names consisting of multiple words should use capital letters at word boundaries

int numberOfTries;double costOfLiving;

Page 9: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 20099

Capitalization in Class Names

Class names generally have the first letter capitalized

Scanner, String

Page 10: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200910

Naming Examples

String sentence;

Scanner keyboard;

String personalGreeting;

YourClass yourObject;

Page 11: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200911

Comments

The best programs are self-documenting

It should be obvious what the program does just by reading the program itself

Page 12: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200912

Comments

Choosing meaningful variables names is sometime not enough

Comments allow the programmer to leave notes in the code to aid in understanding

Page 13: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200913

Comments in Java

Two Types

Single-line comment• Begins with “//”

int i; //this is a single-line comment, write whatever you want

Multi-line comment• Everything within /* */

public class Program { /*

This is a multi-line comment. The compiler will completely ignore this text*/public static void main(String[] args) {

Page 14: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200914

Comments

Using a program header is a great way to give basic information about a program

AuthorDescription of the programInputsOutputs

Page 15: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200915

Comments

You should use comments to explain any non-obvious details in your programs

double radius; //in inchesdouble area; //in square inches

Page 16: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200916

Indentation

Programs have a nested structureYour indentation should reflect this

import java.util.Scanner;public class FirstProgram{ public static void main(String[] args) { System.out.println("Hello out there."); System.out.println("I will add two numbers for you."); System.out.println("Enter two whole numbers on a line:");

int n1, n2;

Scanner keyboard = new Scanner(System.in); n1 = keyboard.nextInt(); n2 = keyboard.nextInt();

System.out.println("The sum of those two numbers is"); System.out.println(n1 + n2); }}

Page 17: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200917

Placement of Braces

Some prefer

public class FirstProgram{ …}

Others prefer

public class FirstProgram { …}

It doesn’t matter what you choose, just be consistent

Page 18: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200918

Using Named Constants

You should always give a name to constants such as PI

It may not be obvious to the reader where such a number comes from

final double PI = 3.14159;

area = PI * radius * radius; //is much clearer thanarea = 3.14159 * radius * radius;

Page 19: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200919

Naming Constants

The style for naming constants if different than for variables

Typically use all caps with underscores separating words

final int DAYS_PER_WEEK = 7;final double MASS_OF_EARTH = 5.9742e24; //kgfinal float INTEREST_RATE = 5.55;

Page 20: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200920

Branching

Sometimes, it is necessary to make decisions in programs

ExampleThe remainder operator can be used to determine if a number n is even or odd

If n%2 equals 0, n is even

If n%2 equals 1, n is odd

Page 21: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200921

Branching

int result = n % 2;

Evaluate

result is 0?

Execute

Print “n is even”

Execute

Print “n is odd”

true false

Page 22: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200922

If-Else Statement

An if-else statement allows us to make decisions in a program

int result = n % 2;

if(result == 0)System.out.println(“That number is even!”);

elseSystem.out.println(“That number is odd!”);

Page 23: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200923

If-Else Example

int n = 2int result = n % 2;

if(result == 0)System.out.println(“That number is even!”);

elseSystem.out.println(“That number is odd!”);

System.out.println(“Finished!”);

result = 0

Page 24: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200924

If-Else Example

int n = 3int result = n % 2;

if(result == 0)System.out.println(“That number is even!”);

elseSystem.out.println(“That number is odd!”);

System.out.println(“Finished!”);

result = 1

Page 25: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200925

Boolean Expressions

(result == 0) is a boolean expression

Boolean expressions evaluate to either true or false

Examples10 > 5, (true)4 > 6, (false)Integers are whole numbers, (true)

Page 26: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200926

Java Comparison Operators

Math

Java Name

= == Equal to

≠ != Not equal to

> > Greater than

≥ >= Greater than or equal to

< < Less than

≤ <= Less than or equal to

Page 27: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200927

If-Else Statement Syntax

Syntaxif(Boolean_Expression)Statement_1

elseStatement_2

If Boolean_Expression is true, Statement_1 is executed; otherwise Statement_2 is executed

Page 28: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200928

Compound Statements

Multiple statements can be included in each branch

Called a compound statementEnclose between {…}

if(Boolean_Expression) {Statements_1

}else { Statements_2}

Page 29: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200929

If without Else

Syntax

if(Boolean_Expression)Statement_1

Example

if(accntBalance < 0) //subtract a fee for overdraftsaccntBalance = accntBalance – FEE;

Page 30: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200930

Common Comparison Mistakes

Don’t confuse the assignment operator (=) with the comparison operator (==)!

if(x == y) //valid

if(x = y) //syntax error

Page 31: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200931

Common Comparison Mistakes

Don’t use a semi-colon here

if(x == y) ; //syntax errorSystem.out.println(“x equals y”);

Page 32: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200932

Common Comparison Mistakes

Don’t use == to compare StringsUse string.equals(A_String) or string.equalsIgnoreCase(A_String)Example

String s1 = keyboard.next(); //read in a stringif(s1.equals(“Hello”))

System.out.println(“The String is Hello.”);else

System.out.println(“The String is not Hello.”);

Page 33: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200933

The && Operator (AND)

We can check for multiple conditions using the && (AND) operator

Meaning is similar to that of English “and”

if (temperature > 50 && temperature < 75) {// walk to school if 50 < temperature < 75

}else {

//otherwise drive to school}

Page 34: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200934

The || Operator (OR)

We can also join boolean expression with || (OR)

Meaning is similar to that of English “or”

boolean raining, runningLate;

…if (raining || runningLate) {

//drive to school}

Page 35: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200935

The ! Operator (NOT)

Boolean negation!false is true!true is false

Example

boolean cloudy;

if (!cloudy) {// walk to school if it’s not cloudy

}

Page 36: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200936

Effect of Boolean Operators

A B A && B

A || B !A

true true true true false

true false false true false

false true false true true

false false false false true

Page 37: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200937

Boolean Expression Examples

Using x = 5, y = 10, z = 15

(x < 5 && y > x)• (false && true) -> false

(x <= 5 || y > x)• (true || true) -> true

(x > 3 || z != 15)• (true || false) -> true

(!(x > 3) && x + y == z)• (false && true) -> false

Page 38: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200938

Avoiding the Negation Op

!(A < B) -->

!(A <= B) -->

!(A > B) -->

!(A >= B) -->

!(A == B) -->

!(A != B) -->

(A >= B)

(A > B)

(A <= B)

(A < B)

(A != B)

(A == B)

It’s best to avoid use of the negation operator (!) when possible

Page 39: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200939

Nested If-Statements

It’s possible to have if statements inside other if statements

if(Boolean_Expression_1) {

if(BooleanExpression_2) {…

}}

Page 40: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200940

Nested If Statements

ExampleWe want to perform some checks on the user’s account balance

If the balance is >= 0, we’ll add interest only if the interest rate is >= 0, and print an error message if interest rate is < 0. If the balance is < 0, we’ll subtract a fee.

Page 41: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200941

Nested If Statements

Evaluate

balance >= 0

Evaluate

INTEREST_RATE >= 0

Execute

balance -= FEE

true false

Execute

balance = balance + balance*INTEREST_RATE

Execute

Print Error Message a

true false

Page 42: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200942

Nested If Statements

if(balance >= 0) {if(INTEREST_RATE >= 0) balance = balance +

INTEREST_RATE*balance;else

System.out.println(“Negative Interest!”);}else

balance = balance – FEE;

Page 43: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200943

Nested If Statements

What if we didn’t need to print the error message?

if(balance >= 0 && INTEREST_RATE >= 0) balance = balance +

INTEREST_RATE*balance;else

balance = balance – FEE;

Page 44: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200944

Multi-Branch If Statements

What if we need to decide between many possibilities?

ExampleGiven a numeric score (0..100) determine whether the grade is an A,B,C,D, or F

Page 45: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200945

Multi-Branch If Statements

A if: score >= 90B if: 90 > score >= 80C if: 80 > score >= 70D if: 70 > score >= 60F in all other cases

Page 46: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200946

Multi-Branch If Statements

We could write this as follows

if(score >=90) grade = ‘A’;else if(score >=80) grade = ‘B’; else if(score >=70) grade = ‘C’; else if(score >=60) grade = ‘D’; else grade = ‘F’;

Page 47: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200947

Multi-Branch If Statements

The preferred way to write this is

if(score >=90)grade = ‘A’;

else if(score >=80)grade = ‘B’;

else if(score >=70)grade = ‘C’;

else if(score >=60)grade = ‘D’;

elsegrade = ‘F’;

Page 48: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200948

Multi-Branch If Statement

Syntax

if(Boolean_Expression_1)Action_1

else if(Boolean_Expression_2) Action_2

…else if(Boolean_Expression_n)

Action_nelseDefault_Action

Page 49: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200949

Programming Demo

Write a program to read in three distinct nonnegative integers from the keyboard and display them in increasing order

Page 50: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200950

Programming Demo

Call the three numbers a,b,c

Designing the algorithmDetermine which of a,b,c is the smallest• If it’s not a, is it b? If it’s not a or b, must be c

Determine which of the two remaining integers is smaller than the other

Page 51: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200951

Programming Demo

Evaluate

a is smallest?

true false

a < b < c

a < c < b

Evaluate

b < ctrue false

b < a < c

b < c < a

Evaluate

a < ctrue false

c < a < b

c < b < a

Evaluate

a < btrue false

Evaluate

b is smallest?

true false

Page 52: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200952

Programming Demo

PseudocodeAsk user for three integers, a,b,cDetermine which of a,b,c is the smallestDetermine which of the remaining two is smallerPrint a,b,c in ascending order

Page 53: COMP 110: Introduction to Programming Tyler Johnson January 28, 2009 MWF 11:00AM-12:15PM Sitterson 014.

COMP 110: Spring 200953

Friday

Recitation

BringLaptop (fully charged)TextbookAny questions about Program 1