chapter 4: basic control structures java programming from the beginning copyright © 2000 w. w....

77
Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4: Basic Control Structures Java Java Programming Programming FROM THE BEGINNING FROM THE BEGINNING Chapter 4 Basic Control Structures

Upload: diane-stone

Post on 19-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

1

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Chapter 4

Basic Control Structures

Page 2: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

2

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Control structure

• IF statement: test and decide based on the test result – need comparison

• need relational and equality operators.

– Logical operators are used to combine the results of multiple comparisons.

• While statement: establish a loop that repeatedly executes a statement or a series of statements.

• Break statement: causes a loop to terminate prematurely.

Page 3: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

3

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.1 Performing Comparisons

• How to test conditions?

whether a boolean expression has the value true or false.

• Most of the conditions comparisons.• Two operators to perform comparisons:

– relational operators

– equality operators.

Page 4: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

4

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Relational Operators

• The relational operators test the relationship between two numbers, returning a boolean result.< Less than> Greater than<= Less than or equal to>= Greater than or equal to

• The relational operators don’t require operands to have identical types.

Page 5: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

5

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Equality Operators

• Testing whether two values are equal or not equal is done using the equality operators:== Equal to!= Not equal to

• Examples of the equality operators:6 == 2 false6 != 2 true2 == 2 true2 != 2 false

Page 6: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

6

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Testing Floating-PointNumbers for Equality

• It is not a good idea to test two double variables are equal because of round-off error.

• For example, the condition

1.2 - 1.1 == 0.1

is false, because the value of 1.2 - 1.1 is 0.09999999999999987, not 0.1.

• One way to avoid problems with round-off error is to test whether floating-point numbers are close enough, rather than testing whether they’re equal.

• That is, try not to test with == for floating-point numbers. Use <= or >= instead.

Page 7: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

7

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Testing Objects for Equality

• If x and y are two object variables of the same type (class):

x == y or x != y

tests whether x and y refer to the same object or null.

• It does not compare the actual contents in x and y.• Use equals() method to compare the contents.

x.equals(y);

Page 8: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

8

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Comparing Strings

• use str1.equals(str2) to test whether str1 and str2 contain the same series of characters.

• The equalsIgnoreCase method is similar to equals but ignores the case of letters.

Page 9: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

9

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Comparing Strings

• To compare the strings str1 and str2, the compareTo method is used:

str1.compareTo(str2)

• compareTo returns an integer (not boolean).– Return less than zero if str1 is less than str2– Return equal to zero if same

– Return greater than zero if str1 is greater than str2

str1= "aab" , str2 = "aba".

Then, str1.compareTo(str2)<0

Page 10: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

10

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Comparing Strings

• To determine whether one character is less than another, the compareTo method examines the Unicode values of the characters.

• Properties of Unicode characters:– Digits are assigned consecutive values; 0 is less than 1,

which is less than 2, and so on.

– Uppercase letters have consecutive values.

– Lowercase letters have consecutive values.

– Uppercase letters are less than lowercase letters.

– The space character is less than any printing character, including letters and digits.

Page 11: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

11

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.2 Logical Operators

• logical operators : used to combine the results of comparisons.

• Example: age >= 18 && age <= 65

• Three logical operators:! Logical not&& Logical and|| Logical or

• ! is a unary operator. && and || are binary operators.

• All logical operators : boolean operands and boolean results.

Page 12: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

12

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Performing the And, Or Operation

• && operator : tests whether two boolean expressions are both true.

• The && operator ignores the right operand if the left operand is false. This behavior is often called short-circuit evaluation.

• || operator: test whether one (or both) of two conditions is true.

• The || operator also relies on short-circuit evaluation. If the left operand is true, it ignores the right operand.

Page 13: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

13

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Performing the Not Operation

• !(true) = false, !(false) = true.Example:

(9 < 11) is true,

!(9 < 11) is false.

• The ! operator is often used to test whether objects (including strings) are not equal:!str1.equals(str2)

Page 14: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

14

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Precedence of Java operators

Give the order for each operator

_____ Arithmetic operators (+, -, *, /)

_____ Relational operators (<,>,<=,>=)

_____ Equality operators(==, !=)

_____! Operator (unary)

_____ && operator

_____ || operator.

Page 15: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

15

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Precedence of Java operators

• ! Operator (unary)• Arithmetic operators (+, -, *, /)• Relational operators (<,>,<=,>=)• Equality operators(==, !=)• && operator• || operator.• Examplea < b || c >= d && e == f

(a < b) || ((c >= d) && (e == f))

Page 16: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

16

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Associativity of And, Or, and Not

• The ! operator is right associative. Ex) !! e is interpreted as (!(! e))

• The && and || operators are left associative.Ex) Java would interpreta < b && c >= d && e == f

as((a < b) && (c >= d)) && (e == f)

Page 17: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

17

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Simplifying boolean Expressions

• de Morgan’s Laws:

!(expr1 && expr2) is equivalent to !(expr1) || !(expr2)

!(expr1 || expr2) is equivalent to !(expr1) && !(expr2)

expr1 and expr2 are arbitrary boolean expressions.

Page 18: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

18

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Why simplify boolean Expressions?

!(i >= 1 && i <= 10)

!(i >= 1) || !(i <= 10)

i < 1 || i > 10

• This version has fewer operators and avoids using the ! operator, which can make boolean expressions hard to understand.

Page 19: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

19

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Testing for Leap Years

• A leap year : a multiple of 4. However, if a year is a multiple of 100, then it must also be a multiple of 400 in order to be a leap year.

• 2000 is a leap year, but 2100 is not.• Can you make a statement? (year % 4 == 0) &&(if year % 100 == 0, then year % 400 == 0)

Since ab equals (not a) or b

(year % 4 == 0) &&(year % 100 != 0 || year % 400 == 0)

Page 20: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

20

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

if(boolean expression)

{

statements

}

amount>balance

System.out.println(“You cannot withdraw”);

True

False

4.3 Simple if Statements

Page 21: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

21

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The Empty Statementif (score > 100); // empty statement score = 100;

• The compiler treats the extra semicolon as an empty statement, however, so it doesn’t detect an error:if (score > 100) ; // Empty statement--does nothingscore = 100;

Page 22: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

22

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using {}if(expression) one statement;

if(expression){ multiple statements; more statements;}

• Be careful with indentation• I recommend always using {}• Block: a series of statements enclosed within {}

Page 23: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

23

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

if(amount>balance)

{

System.out.println(“You cannot withdraw”);

} else {

balance -= amount;

}

amount>balanceSystem.out.println(“You cannot withdraw”);

True False

balance -= amount;

4.4 if Statements with else Clauses

Page 24: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

24

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

if Statement Layout

• An example of an if statement with an else clause:if (a > b) larger = a;else larger = b;

• Layout conventions:– Align else with if.

– Put each assignment on a separate line.

– Indent each assignment.

Page 25: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

25

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

if Statement Layout

• Recommended layout when the inner statements are blocks:if (…) { …} else { …}

• Other layouts are also common. For example:if (…) { …}else { …}

Page 26: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

26

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Cascaded if Statements

• To test a series of conditions one by one until finding one that’s true.

• Use nesting a series of if statements in such a way that the else clause of each is another if statement.

• This is called a cascaded if statement.• Note there is not elseif keyword in Java.• Should give a space between.

Page 27: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

27

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Cascaded if StatementsMake a statement based on the design.

If score >= 90: give A

If score >= 80 and < 90, give B

If score >= 70 and < 80, give C

If score >= 60 and < 70, give D

If score >= 0 and < 60, give F

Page 28: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

28

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Cascaded if Statements

if (score >= 90) System.out.println("A");else if (score >= 80 && score < 90) System.out.println("B"); else if (score >= 70 && score < 80) System.out.println("C"); else if (score >= 60 && score < 70) System.out.println("D"); else System.out.println("F");

Page 29: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

29

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Cascaded if Statements

• To avoid “indentation creep” :if (score >= 90) System.out.println("A");else if (score >= 80 && score < 90) System.out.println("B");else if (score >= 70 && score < 80) System.out.println("C");else if (score >= 60 && score < 70) System.out.println("D");else System.out.println("F");

Page 30: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

30

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Simplifying Cascaded if Statementsif (score >= 90) System.out.println("A");else if (score >= 80) System.out.println("B");else if (score >= 70) System.out.println("C");else if (score >= 60) System.out.println("D");else System.out.println("F");

• What happens if I reverse the order?

Page 31: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

31

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Program: Flipping a Coin

• Write a program that asks the user to guess the outcome of a simulated coin flip.Enter heads or tails: tails ( user input)

Sorry, you lose.

• If the user’s input isn’t heads or tails (ignoring case), the program will print an error message and terminate.

Enter heads or tails: hed ( user input)

Sorry, you didn't enter heads or tails; please try again.

Page 32: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

32

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

How to generate random?

• Math.random method returns a “random” number (technically, a pseudorandom number).

0.0<= random<1.0• Design: (pseudo code)

if (Math.random()<0.5) result = heads;

else result = tails;

Page 33: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

33

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

CoinFlip.java

• After reading the user’s input, the program validates it, to make sure that it meets the requirements of the program.

Page 34: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

34

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

if(score >= 60)

if(score >= 80)

System.out.println(“Good job!”);

else

System.out.println(“You did not pass”);

• Ambiguity: two or more possible interpretations.

• “Dangling else” problem may occur when more if than else.

• When if statements are nested, Java matches each else clause with the nearest unmatched if.

• Bad indentation

– better to use {} ALWAYS!

The “Dangling else” Problem

Page 35: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

35

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.5 The boolean Type

• Other uses of boolean type:– Variables and parameters

– methods can return boolean values.

– representing data items that have only two possible values.

• For example: in the CoinFlip program, the user’s choice (heads or tails) could be boolean variable:boolean headsWasSelected;

Or

headsWasSelected = userInput.equalsIgnoreCase("heads");

• Good names for boolean variables often contain a verb such as “is,” “was,” or “has.”

Page 36: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

36

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Testing and displaying a boolean Variable

if (headsWasSelected) …

rather thanif (headsWasSelected == true) …

if (!headsWasSelected) …

rather thanif (headsWasSelected == false) …

Display

System.out.println(headsWasSelected);

Output: true or false

Page 37: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

37

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.6 Loops

• Loop: a language construct that repeatedly performs an action.

• In Java, loop has

1) loop body: a statement to be repeated.

2) controlling expression: a condition to be checked

• Each time the loop body is executed, the controlling expression is checked. – If the expression is true, the loop continues to execute.

– If it’s false, the loop terminates.

• Iteration: a single cycle of the loop.

Page 38: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

38

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Types of Loops

• Java has three loop statements:– While : condition is tested before executing the

loop body– Do : tests its condition after executing the loop body– for : used if the loop is controlled by a variable whose

value needs to be updated each time the loop body is executed.

• Which type of loop to use is mostly a matter of convenience.

Page 39: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

39

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

The while Statement

• Form of the while statement:while ( expression ) statement

• The controlling expression must have boolean type. The loop body can be any statement.

• Example:while (i < n) // Controlling expression i *= 2; // Loop body

Page 40: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

40

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

While flowchart

while(condition){

statements

}

i < n

i *= 2;

True

False

Page 41: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

41

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Infinite loopswhile(!input.equals(“QUIT”)) {

System.out.println(“You entered “ + input);

}

• What is the problem?

Page 42: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

42

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Infinite loopswhile(!input.equals(“QUIT”)) {

System.out.println(“You entered “ + input);

}

• This loop never ends! – The variable that controls the loop (input) is never changed.

– What should we do?

while(!input.equals(“QUIT”)) {

System.out.println(“You entered “ + input);

input = console.readLine();

}

• Continue to do the same thing many times, until some condition has been met

Page 43: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

43

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Blocks as Loop Bodies

• Repeat more than one statement use block {}.

• Case study: Finding the greatest common divisor (GCD).

• Definition of GCD: the largest integer that divides both numbers evenly, with no remainder.

• For example, the GCD of 15 and 35 is 5.• Choose or search an algorithm and implement it

with java.

Page 44: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

44

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Blocks as Loop Bodies

• Euclid’s algorithm for computing the GCD:1. Let m and n be variables containing the two numbers.

2. If n is 0, then stop: m is the GCD.

3. Divide m by n. Save the divisor in m, and save the remainder in n.

4. Repeat the process, starting at step 2.

• How to write a program?– Write a pseudo code.

Page 45: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

45

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Blocks as Loop Bodieswhile (n != 0) { m = n; // Save divisor in m n = m%n; // Save remainder in n}

What is wrong?

while (n != 0) { r = m % n; // Store remainder in r m = n; // Save divisor in m n = r; // Save remainder in n}

Page 46: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

46

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Declaring Variables in Blocks

• A temporary variable can be declared inside a block:while (n != 0) { int r = m % n; // Store remainder in r m = n; // Save divisor in m n = r; // Save remainder in n}

• Declaring a variable inside a block isn’t always a good idea.– The variable can be used only within the block.– A variable declared in a block is created each time the block is

entered and destroyed at the end of the block, causing its value to be lost.

Page 47: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

47

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Example: Improvingthe Fraction Constructor

• The original version of the Fraction class provides the following constructor:public Fraction(int num, int denom) { numerator = num; denominator = denom;}

• This constructor doesn’t reduce fractions to lowest terms. Executing the statementsFraction f = new Fraction(4, 8);System.out.println(f);

will produce 4/8 as the output instead of 1/2.

Page 48: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

48

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Example: Improvingthe Fraction Constructor

• An improved version of the Fraction constructor:public Fraction(int num, int denom) { // Compute GCD of num and denom int m = num, n = denom; while (n != 0) { int r = m % n; m = n; n = r; }

// Divide num and denom by GCD; store results in instance // variables if (m != 0) { numerator = num / m; denominator = denom / m; }

Page 49: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

49

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Example: Improvingthe Fraction Constructor

// Adjust fraction so that denominator is never negative if (denominator < 0) { numerator = -numerator; denominator = -denominator; }}

• If the GCD of num and denom is 0 (then both are 0), this constructor doesn’t assign values to numerator and denominator. Java automatically initializes these variables to 0 anyway, so there is no problem.

Page 50: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

50

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.7 Counting Loops

• counter: a variable whose value increases or decreases systematically each time through the loop.

• Many loops require counter.

Page 51: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

51

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

A “Countdown” Loop

• Consider the problem of writing a loop that displays a countdown: can you write a program?T minus 10 and countingT minus 9 and countingT minus 8 and countingT minus 7 and countingT minus 6 and countingT minus 5 and countingT minus 4 and countingT minus 3 and countingT minus 2 and countingT minus 1 and counting

Page 52: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

52

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

A “Countdown” Loop

• Need a counter:int i = 10;while (i > 0) { System.out.println("T minus " + i + " and counting"); i -= 1;}

Page 53: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

53

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Counting Up• How to write a program using while?:1 12 43 94 165 25

int i = 1;while (i <= n) { System.out.println(i + " " + i * i); i += 1;}

Page 54: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

54

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Counter Variables

• counters should be int, not double.• Using short names for counters is a tradition (for

example, i, j, k) .

Page 55: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

55

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Increment and decrement

• Increase by 1 or decrease by 1.• One way i = i + 1; // Increment ii = i - 1; // Decrement i

• Another way : compound assignmenti += 1; // Increment ii -= 1; // Decrement I

• Or use increment, decrement operators

increment: ++i;(prefix) or i++; (postfix )

decrement: --i;(prefix) or i--; (postfix )

Page 56: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

56

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Increment and Decrement Operators

• Differences between prefix and postfix?

System.out.println(++i);// Increments i and then prints the new

// value of iSystem.out.println(i++);// Prints the old value of i and then// increments i

Page 57: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

57

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Increment and Decrement Operators

• ++ and -- can be used in conjunction with other operators: What is i and j at the end of the following?i = 1;j = ++i + 1;

i is now 2 and j is now 3.

i = 1;j = i++ + 1;

Both i and j are now 2.

Page 58: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

58

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Side Effects

• The ++ and -- operators don’t behave like normal arithmetic operators.

• Evaluating the expression i + j doesn’t change i or j. Evaluating ++i causes a permanent change to i, however.

• The ++ and -- operators are said to have a side effect, because these operators do more than simply produce a result.

Page 59: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

59

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Using the Increment andDecrement Operators in Loops

• Update loop counters.• while (i > 0) {

System.out.println("T minus " + i + " and counting"); i--;}

• while (i <= n) { System.out.println(i + " " + i * i); i++;}

• while (i > 0) { System.out.println("T minus " + i-- + " and counting");}

Page 60: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

60

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Program: Counting Coin Flips

• The CountFlips program will flip an imaginary coin any number of times.

• After the user enters the number of flips desired, CountFlips will print the number of heads and the number of tails:Enter number of flips: 10Number of heads: 6Number of tails: 4

Page 61: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

61

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

A Coin-Flipping Loop

• There are several ways to write a loop that flips a coin n times.

• Two possibilities: Technique 1 Technique 2

int i = 1;while (i <= n) { while (n > 0) { … … i++; n--;} }

• The first technique preserves the value of n. The second avoids using an additional variable.

Page 62: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

62

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

CountFlips.java// Counts the number of heads and tails in a series of coin// flips

import jpb.*;

public class CountFlips { public static void main(String[] args) { // Prompt user to enter number of flips SimpleIO.prompt("Enter number of flips: "); String userInput = SimpleIO.readLine(); int flips = Integer.parseInt(userInput);

Page 63: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

63

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

// Flip coin for specified number of times int heads = 0, tails = 0; while (flips > 0) { if (Math.random() < 0.5) heads++; else tails++; flips--; }

// Display number of heads and tails System.out.println("Number of heads: " + heads); System.out.println("Number of tails: " + tails); }}

Page 64: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

64

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

A Possible Modification

• An alternate version of the while loop:while (flips-- > 0) if (Math.random() < 0.5) heads++; else tails++;

Page 65: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

65

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.8 Exiting from a Loop:The break Statement

• Java’s break statement allows a loop to terminate at any point.• Form of the break statement:

break;• Terminate immediately.• Each break statement is usually nested inside an if statement.While (n>0){………

if (userInput.equal(“N”))break;

……………n--;

}

Page 66: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

66

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Uses of the break Statement

• The break statement has several potential uses:– Premature exit from a loop– Exit from the middle of a loop– Multiple exit points within a loop

Page 67: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

67

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Premature Exit from a Loop

• Testing whether a number is prime.• The following loop breaking out when a divisor is

found:int d = 2;while (d < n) { if (n % d == 0) break; // Terminate loop; n is not a prime d++;}if (d < n) System.out.println(n + " is divisible by " + d);else System.out.println(n + " is prime");

Page 68: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

68

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Loops with an Exit in the Middle

• A loop that reads user input, terminating when a particular value is entered:

while (true) { SimpleIO.prompt("Enter a number (enter 0 to stop): "); String userInput = SimpleIO.readLine(); int n = Integer.parseInt(userInput); if (n == 0) break; System.out.println(n + " cubed is " + n * n * n);}

• Using true as the controlling expression forces the loop to repeat until the break statement is executed.

Page 69: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

69

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.10 Debugging

• It will be necessary to run the program more than once, with different input data each time.

• test case : each set of input data.• statement coverage : a testing technique of

making sure that each statement in the program is executed by at least one test case.

• For if, while statements, test each true and false case.

Page 70: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

70

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Debugging Loops

• Common types of loop bugs:– “Off-by-one” errors. Possible cause: Using the wrong

relational operator in the loop’s controlling expression (such as i < n instead of i <= n). One more iteration.

– Infinite loops. Possible causes: Failing to increment (or decrement) a counter inside the body of the loop. Accidentally creating an empty loop body by putting a semicolon in the wrong place.

– Never-executed loops. Possible causes: Inverting the relational operator in the loop’s controlling expression (i > n instead of i < n, for example). Using the == operator in a controlling expression.

Page 71: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

71

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

4.9 Case Study: DecodingSocial Security Numbers

• The first three digits of a Social Security Number (SSN) form the “area number,” which indicates the state or U.S. territory in which the number was originally assigned.

• The SSNInfo program will ask the user to enter an SSN and then indicate where the number was issued:Enter a Social Security number: 078-05-1120Number was issued in New York

Page 72: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

72

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Input Validation

• SSNInfo will partially validate the user’s input:– The input must be 11 characters long (not counting any

spaces at the beginning or end).

– The input must contain dashes in the proper places.

• There will be no check that the other characters are digits.

Page 73: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

73

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Input Validation

• If an input is invalid, the program will ask the user to re-enter the input:Enter a Social Security number: 078051120Error: Number must have 11 characters

Please re-enter number: 07805112000Error: Number must have the form ddd-dd-dddd

Please re-enter number: 078-05-1120Number was issued in New York

Page 74: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

74

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Design of the SSNInfo Program

• An overall design for the program:1. Prompt the user to enter an SSN and trim spaces from the input.

2. If the input isn’t 11 characters long, or lacks dashes in the proper places, prompt the user to re-enter the SSN; repeat until the input is valid.

3. Compute the area number from the first three digits of the SSN.

4. Determine the location corresponding to the area number.

5. Print the location, or print an error message if the area number isn’t legal.

Page 75: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

75

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Design of the SSNInfo Program

• A pseudocode version of the loop in step 2:while (true) { if (user input is not 11 characters long) { print error message; else if (dashes are not in the right places) { print error message; else break; prompt user to re-enter input; read input;}

Page 76: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

76

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

Design of the SSNInfo Program

• The input will be a single string, which can be trimmed by calling the trim method.

• The first three digits of this string can be extracted by calling substring and then converted to an integer by calling Integer.parseInt.

• This integer can then be tested by a cascaded if statement to see which location it corresponds to.

Page 77: Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic

Copyright © 2000 W. W. Norton & Company.All rights reserved.

77

Chapter 4: Basic Control Structures

JavaJava ProgrammingProgrammingFROM THE BEGINNINGFROM THE BEGINNING

SSNInfo.java