0% found this document useful (0 votes)
59 views54 pages

Object - Oriented System Design

Uploaded by

Jinwoo Song
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views54 pages

Object - Oriented System Design

Uploaded by

Jinwoo Song
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Object – Oriented System Design

Lab #2
Contents
• Flow Control
– Branching Statements
– Looping Statements

2
Flow Control
• An application may use various flow control statements to direct
the logic of its execution

• Two form of flow control statements are:


– Branching Statements
• if, if – else, if else-if;
• switch

– Looping Statements
• while
• do-while
• for

3
Branching Statements
• Branch statements are used to divert the execution based on the
Boolean results of a condition

Program flow
Program flow

Switch
If condition condition

Case 1 Default
Case 2 Case 4
True False
Case 3

4
if Statements
• If statements allow one of two branch direction
– if (boolean condition)
statement;
• Multiple statements can be executed by including them within { }
– if (boolean condition)
{
statement1;
statement2;
statement3;
}
• The statements within the if statement are executed if the
condition is true
• If the condition is false, the statements are ignored and the flow
of the program continues after the statements.

5
if else-if Statements
• It is sometimes necessary to combine multiple if statements.
• Use if else-if statements to combine if conditions

– if (boolean condition)
statement1;
else if (boolean condition2)
statement2;
else
statement3;

• Using a combination of if else-if and else statements it is possible


to code complex conditions

6
if else Statements

7
switch Statements
• Switch statements allow for multiway branching
• Switch statements comprise of specific parts
– The switch: switch and control statements
– The cases: each case that must be considered by the switch
– The default case: if none of the case fit then the default case will match

• switch-case blocks should have break statements within each case


to finish the case

8
switch Statements (Contd)

Controlling Expression

Case Labels

9
switch Statements (Contd)
• There are special considerations when using switch statements.
– The controlling expression must evaluate to one of the following types
• Char
• Int
• Short
• Byte
• Enum
• String (As of Java 7. Not available if you use an older version of java)

– The case labels must all be of the same type as the controlling
expression
– The case labels are followed by colons :

10
switch Statements (Contd)
• Omitting the breaks;
– Execution “falls through” to the next case statement after the end of the
statement is reached

Case 2
Case 3
Case 4

11
Self-Test (1)
• Template 폴더 업데이트
– 이전에 Clone 한 Template 폴더에 변경사항을 업데이트 하기 위해서는 다
시 Clone 하지 않고 다른 명령어를 사용한다.
– 설치한 Git 프로그램을 통해 Clone 한 Template 폴더에 접근
– git pull 명령어 입력
– 이후 Template 폴더를 확인하면 웹사이트와 동일하게 파일이 업데이트 된
것을 확인할 수 있다.

12
Self-Test (1)
❖ 프로젝트 명: Project02_1
❖ git commit -m “Project02_1”
❖ 당일 밤 12시까지 제출

• int type 변수 n의 값을 키보드를 통해 입력 받은 후, 입력 받은 n의


값이 어느 범위에 속하는지 판단하는 프로그램을 작성할 것
– 𝑛<0
• 출력: n is less than 0
– 0 ≤ 𝑛 < 100
• 출력: n is greater than or equal to 0 and less than 100
– 𝑛 ≥ 100
• 출력: n is greater than or equal to 100

13
Loop Statements
• Loops are control structures that allow groups of code to be
repeated a number of times
• The statement or group of statements to be repeated is called
body of the loop
• Each time a loop repeats is called an iteration of the loop

14
Loop Statements (Contd)
• Control of loop: ICU
1. Initialization
2. Condition for termination (continuing)
3. Updating the condition
• Body of loop

15
Loop Statements (Contd)
• the while loop
• the do-while loop
• the for loop

16
while Statement
• Also called a while loop

• A controlling boolean expression


– True -> repeats the statements in the loop body
– False -> stops the loop
– Initially false (the very first time)
• loop body will not even execute once

17
while Statement (Contd)
• Syntax

while (boolean_expression)
body_statement

/*-------------------------------------------------------------------------*/

while (boolean_expression)
{
first_statement
second_statement
...
}

18
while Statement (Contd)

19
while Statement (Contd)
• class WhileDemo

20
do-while Statement
• Also called do-while loop (repeat-until loop)
• similar to a while statement
– except that the loop body is executed at least once
• syntax
do
body_statement
while (boolean_expression);

– don’t forget the semicolon at the end

21
do-while Statement (Contd)
• First, the loop body is executed
• Then the boolean expression is checked
– As long as it is true, the loop is executed again
– If it is false, the loop exits
• Equivalent while statement
body_statement(s)
while (boolean_condition)
body_statement(s)

22
do-while Statement (Contd)

23
do-while Statement (Contd)
• class DoWhileDemo

24
Infinite Loops
• A loop which repeats without ever ending

• The controlling boolean expression (condition to continue)


– never becomes false

25
for Statement
• A for statement executes the body of a loop a fixed number of
times

• example
for (count = 1; count < 3; count++)
System.out.println(count);
System.out.println(“Done”);

26
for Statement (Contd)
• Syntax
for (Initialization; Condition; Update)
body_statement
body_statement
• a simple statement or
• a compound statement in {}
• Corresponding while statement
Initialization
while (Condition)
body_statement_including_update

27
for Statement (Contd)

28
for Statement (Contd)
• class ForDemo

--

29
Choosing a Loop Statement
• If you know how many times the loop will be iterated, use a for
loop

• If you don’t know how many times the loop will be iterated, but
– It could be zero, use a while loop
– It will be at least once, use a do-while loop

• Generally, a while loop is a safe choice

30
Programming with Loops: Outline
• The Loop Body
• Initializing Statements
• Ending a Loop

31
Loop Body
• To design the loop body, write out the actions the code must
accomplish

• Then look for a repeated pattern


– The pattern need not start with the first action
– The repeated pattern will form the body of the loop
– Some actions may need to be done after the pattern stops repeating

32
Initializing Statements
• Some variables need to have a value before the loop begins
– Sometimes this is determined by what is supposed to happen after one
loop iteration
– Often variables have an initial value of zero or one, but not always

• Other variables get values only while the loop is iterating

33
Ending a Loop
• If the number of iterations is known before the loop starts, the
loop is called a count-controlled loop
– Use a for loop

• Asking the user before each iteration if it is time to end the loop
is called the ask-before-iterating technique
– Appropriate for a small number of iterations
– Use a while loop or a do-while loop

34
Ending a Loop (Contd)
• For large input lists, a sentinel value can be used to signal the
end of the list
– The sentinel value must be different from all the other possible inputs
– A negative number following a long list of non-negative exam score
could be suitable
• 90
• 0
• 10
• -1 <= exam’s score cannot be a negative, so this score is sentinel value

35
Ending a Loop (Contd)
• Example – reading a list of scores followed by a sentinel value

int next = keyboard.nextInt();


while (next >= 0)
{
Process_The_Score
next = keyboard.nextInt();
}

36
Ending a Loop (Contd)
• class ExamAverager

37
Nested Loops
• The body of a loop can contain any kind of statements, including
another loop

• In the previous example


– The average score was computed using a while loop
– This while loop was placed inside a do-while loop so the process could
be repeated for other sets of exam scores.

38
Nested Loops (Contd)

for (line = 0; line < 4; line++)


{ body of
for (star = 0; star < 5; star++) outer loop

System.out.print(‘*’);
System.out.println(); body of
inner loop
}

• Each time the outer loop body is executed, the inner loop body
will execute 5 times
• 20 times total
*****
*****
Output: *****
*****

39
Programming Example:

Output:

40
Precedence and Associativity Rules

41
Flow of Control
• As in most programming languages, flow of control in Java
refers to its branching and looping mechanisms
• Java has several branching mechanisms: if-else, if, and
switch statements
• Java has three types of loop statements: the while, do-
while, and for statements
• Most branching and looping statements are controlled by
Boolean expressions
– A Boolean expression evaluates to either true or false
– The primitive type boolean may only take the values true or
false

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-42


Display 3.1 Tax Program
import java.util.Scanner; if (netIncome <= 15000)
tax = 0;
public class IncomeTax else if ((netIncome > 15000) && (netIncome <=
{ 30000))
public static void main(String[] args) //tax = 5% of amount over $15,000
{ tax = (0.05*(netIncome - 15000));
Scanner keyboard = new Scanner(System.in); else //netIncome > $30,000
double netIncome, tax, fivePercentTax, {
tenPercentTax; //fivePercentTax = 5% of income from $15,000
to $30,000.
System.out.println("Enter net income.\n" fivePercentTax = 0.05*15000;
+ "Do not include a dollar sign or any //tenPercentTax = 10% of income over
commas."); $30,000.
netIncome = keyboard.nextDouble( ); tenPercentTax = 0.10*(netIncome - 30000);
tax = (fivePercentTax + tenPercentTax);
}

System.out.printf("Tax due = $%.2f", tax);


}
}

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-43


Display 3.1 Tax Program

Enter net income.


Do not include a dollar sign or any commas.
40000
Tax due = $1750.00

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-44


Display 3.2 A switch Statement
import java.util.Scanner; switch (numberOfFlavors)
{
public class SwitchDemo case 32:
{ System.out.println("Nice selection.");
public static void main(String[] args) break;
{ case 1:
Scanner keyboard = System.out.println("I bet it's vanilla.");
new Scanner(System.in); break;
case 2:
System.out.println("Enter number of case 3:
ice cream flavors:"); case 4:
int numberOfFlavors = keyboard.nextInt( ); System.out.println(numberOfFlavors + " flavors");

System.out.println("is acceptable.");
break;
default:
System.out.println("I didn't plan for");
System.out.println(numberOfFlavors + " flavors.");
break;
}
}
}
Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-45
Display 3.2 A switch Statement

Enter number of ice cream flavors:


1
I bet it’s vanilla.

Enter number of ice cream flavors:


32
Nice selection.

Enter number of ice cream flavors:


3
3 flavors
is acceptable.

Enter number of ice cream flavors:


9
I didn’t plan for 9 flavors.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-46


Pitfall: Using == with Strings
• The equality comparison operator (==) can correctly test two
values of a primitive type
• However, when applied to two objects such as objects of the
String class, == tests to see if they are stored in the same
memory location, not whether or not they have the same
value
• In order to test two strings to see if they have equal values,
use the method equals, or equalsIgnoreCase
string1.equals(string2)
string1.equalsIgnoreCase(string2)

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-47


Display 3.4 Comparing Strings
public class StringComparisonDemo String s3 = "A cup of java is a joy forever.";
{ if (s3.compareToIgnoreCase(s1) < 0)
public static void main(String[] args) {
{ System.out.println("\"" + s3 + "\"");
String s1 = "Java isn't just for breakfast."; System.out.println("precedes");
String s2 = "JAVA isn't just for breakfast."; System.out.println("\"" + s1 + "\"");
System.out.println("in alphabetic
if (s1.equals(s2)) ordering");
System.out.println("The two lines are equal."); }
else else
System.out.println("The two lines are not equal."); System.out.println("s3 does not
precede s1.");
if (s2.equals(s1)) }
System.out.println("The two lines are equal."); }
else
System.out.println("The two lines are not equal.");

if (s1.equalsIgnoreCase(s2))
System.out.println("But the lines are equal, ignoring case.");
else
System.out.println("Lines are not equal, even ignoring case.");

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-48


Display 3.4 Comparing Strings

The two lines are not equal.


The two lines are not equal.
But the lines are equal, ignoring case.
“A cup of java is a joy forever.”
precedes
“Java isn’t just for breakfast.”
in alphabetical ordering

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-49


Loops
• Loops in Java are similar to those in other high-level
languages
• Java has three types of loop statements: the while,
the do-while, and the for statements
– The code that is repeated in a loop is called the body of the
loop
– Each repetition of the loop body is called an iteration of
the loop

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-50


Display 3.7 Demonstration of while Loops and
do-while Loops
public class WhileDemo
{
public static void main(String[] args)
{ System.out.println("First do-while loop:");
int countDown; countDown = 3;
do
System.out.println("First while loop:"); {
countDown = 3; System.out.println("Hello");
while (countDown > 0) countDown = countDown - 1;
{ }while (countDown > 0);
System.out.println("Hello");
countDown = countDown - 1; System.out.println("Second do-while loop:");
} countDown = 0;
do
System.out.println("Second while loop:"); {
countDown = 0; System.out.println("Hello");
while (countDown > 0) countDown = countDown - 1;
{ }while (countDown > 0);
System.out.println("Hello"); }
countDown = countDown - 1; }
}

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-51


Display 3.7 Demonstration of while Loops and
do-while Loops

First while loop:


Hello
Hello
Hello
Second while loop:
First do-while loop:
Hello
Hello
Hello
Second do-while loop:
Hello

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 3-52


Self-Test (2)
❖ 프로젝트 명: Project02_2
❖ git commit -m “Project02_2”
❖ 당일 밤 12시까지 제출
• 다음과 같은 프로그램을 작성할 것
– 2개의 int type 변수 intVal1, intVal2를 선언한 후 다음과 같이 곱하여 출력할 것
• 1 multiplied by 5 = 5
• 1 multiplied by 4 = 4
• 1 multiplied by 3 = 3
• 1 multiplied by 2 = 2
• 1 multiplied by 1 = 1
...
• 5 multiplied by 5 = 25
• 5 multiplied by 4 = 20
• 5 multiplied by 3 = 15
• 5 multiplied by 2 = 10
• 5 multiplied by 1 = 5
– 곱셈의 왼쪽 피연산자는 intVal1이며 1부터 5까지 순으로 정수형 값을 가짐
– 곱셈의 오른쪽 피연산자는 intVal2이며 5부터 1까지 순으로 정수형 값을 가짐

53
Self-Test (2)

54

You might also like