0% found this document useful (0 votes)
11 views

Lecture 6

Uploaded by

WAFA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Lecture 6

Uploaded by

WAFA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

if/else with return

// Returns the larger of the two given integers.


public static int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}

• Methods can return different values using if/else


– Whichever path the code enters, it will return that value.
– Returning a value causes a method to immediately exit.
– All paths through the code must reach a return statement.

1
All paths must return
public static int max(int a, int b) {
if (a > b) {
return a;
}
// Error: not all paths return a value
}

• The following also does not compile:


public static int max(int a, int b) {
if (a > b) {
return a;
} else if (b >= a) {
return b;
}
}

– The compiler thinks if/else/if code might skip all paths, even
though mathematically it must choose one or the other.
2
if/else, return question
• Write a method quadrant that accepts a pair of real numbers
x and y and returns the quadrant for that point:
y+

quadrant 2 quadrant 1

x- x+

quadrant 3 quadrant 4

y-

– Example: quadrant(-4.2, 17.3) returns 2


• If the point falls directly on either axis, return 0.
3
if/else, return answer
public static int quadrant(double x, double y) {
if (x > 0 && y > 0) {
return 1;
} else if (x < 0 && y > 0) {
return 2;
} else if (x < 0 && y < 0) {
return 3;
} else if (x > 0 && y < 0) {
return 4;
} else { // at least one coordinate equals 0
return 0;
}
}

4
Cumulative algorithms
Adding many numbers
• How would you find the sum of all integers from 1-1000?

// This may require a lot of typing


int sum = 1 + 2 + 3 + 4 + ... ;
System.out.println("The sum is " + sum);

• What if we want the sum from 1 - 1,000,000?


Or the sum up to any maximum?
– How can we generalize the above code?

6
Cumulative sum loop
int sum = 0;
for (int i = 1; i <= 1000; i++) {
// sum = sum + i;
sum+=i;
}
System.out.println("The sum is " + sum);

• cumulative sum: A variable that keeps a sum in progress and


is updated repeatedly until summing is finished.

– The sum in the above code is an attempt at a cumulative sum.

– Cumulative sum variables must be declared outside the loops that


update them, so that they will still exist after the loop.
7
Cumulative product
• This cumulative idea can be used with other operators:
int product = 1;
for (int i = 1; i <= 10; i++) {
product = product * 2;
}
i=1 product=1*2;
i=2 product=2*2=4;
i=3 product=4*2=8;……

System.out.println("2 ^ 10 = " + product);

– How would we make the base and exponent adjustable?

8
Scanner and cumul. sum
• We can do a cumulative sum of user input:

Scanner console = new Scanner(System.in);


int sum = 0;
for (int i = 1; i <= 100; i++) {
System.out.print("Type a number: ");
sum = sum + console.nextInt();
}
System.out.println("The sum is " + sum);

9
if/else, return question
• Write a method countFactors that returns
the number of factors of an integer.
– countFactors(24) returns 8 because
1, 2, 3, 4, 6, 8, 12, and 24 are factors of 24.
Solution:
// Returns how many factors the given number has.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of number
}
}
return count;
}
10
Text Processing

11
Type char
• char : A primitive type representing single characters.
– A String is stored internally as an array of char

String s = "Ali G."; index 0 1 2 3 4 5


value 'A' 'l' 'i' ' ' 'G' '.'

– It is legal to have variables, parameters, returns of type char


• surrounded with apostrophes: 'a' or '4' or '\n' or '\''
char letter = 'P';
System.out.println(letter); // P
System.out.println(letter + " Diddy"); // P Diddy

12
The charAt method
• The chars in a String can be accessed using the charAt method.
– accepts an int index parameter and returns the char at that index

String food = "cookie";


char firstLetter = food.charAt(0); // 'c'
System.out.println(firstLetter + " is for " + food);

• You can use a for loop to print or examine each character.


String major = "CSE";
for (int i = 0; i < major.length(); i++) { // output:
char c = major.charAt(i); // C
System.out.println(c); // S
} // E

13
Comparing char values
• You can compare chars with ==, !=, and other operators:
String word = console.next(); “Tugces”
char last = word.charAt(word.length() - 1);
if (last == 's’) { 6
System.out.println(word + " is plural.");
}

// prints the alphabet


for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c);
}

14
char vs. int
• Each char is mapped to an integer value internally
– Called an ASCII value

'A' is 65 'B' is 66 ' ' is 32


'a' is 97 'b' is 98 '*' is 42

– Mixing char and int causes automatic conversion to int.


'a' + 10 is 107, 'A' + 'A' is 130

– To convert an int into the equivalent char, type-cast it.


(char) ('a' + 2) is 'c'

15
char vs. String
• "h" is a String, but 'h' is a char (they are different)

• A String is an object; it contains methods.


String s = "h";
s = s.toUpperCase(); // "H"
int len = s.length(); // 1
char first = s.charAt(0); // 'H'

• A char is primitive; you can't call methods on it.


char c = 'h';
c = c.toUpperCase(); // ERROR
s = s.charAt(0).toUpperCase(); // ERROR

16
Formatting text with printf
System.out.printf("format string", parameters);

• A format string can contain placeholders to insert parameters:


– %d integer
– %f real number
– %s string
• these placeholders are used instead of + concatenation

– Example:
int x = 3;
int y = -17;
System.out.printf("x is %d and y is %d!\n", x, y);
// x is 3 and y is -17!
•printf does not drop to the next line unless you write \n 17
printf width
– %Wd integer, W characters wide, right-aligned
– %-Wd integer, W characters wide, left-aligned
– %Wf real number, W characters wide, right-aligned
– ...

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 10; j++) {
System.out.printf("%4d", (i * j));
}
System.out.println(); // to end the line
}

Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
18
printf precision
– %.Df real number, rounded to D digits after decimal
– %W.Df real number, W chars wide, D digits after decimal
– %-W.Df real number, W wide (left-align), D after decimal

double gpa = 3.253764;


System.out.printf("your GPA is %.1f\n", gpa);
System.out.printf("more precisely: %8.3f\n", gpa);

Output:
3
your GPA is 3.3
more precisely: 3.254

19
printf question
• Modify our Receipt program to better format its output.
– Display results in the format below, with $ and 2 digits after .

• Example log of execution:


How many people ate? 4
Person #1: How much did your dinner cost? 20.00
Person #2: How much did your dinner cost? 15
Person #3: How much did your dinner cost? 25.0
Person #4: How much did your dinner cost? 10.00

Subtotal: $70.00
Tax: $5.60
Tip: $10.50
Total: $86.10

20
printf answer (partial)
...
// Calculates total owed, assuming 8% tax and 15% tip
public static void results(double subtotal) {
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;
// System.out.println("Subtotal: $" + subtotal);
// System.out.println("Tax: $" + tax);
// System.out.println("Tip: $" + tip);
// System.out.println("Total: $" + total);
System.out.printf("Subtotal: $%.2f\n", subtotal);
System.out.printf("Tax: $%.2f\n", tax);
System.out.printf("Tip: $%.2f\n", tip);
System.out.printf("Total: $%.2f\n", total);
}
}

21
Comparing strings
• Relational operators such as < and == fail on objects.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name == "Barney") {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}

– This code will compile, but it will not print the song.

– == compares objects by references (seen later), so it often gives


false even when two Strings have the same letters.

22
The equals method
• Objects are compared using a method named equals.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name.equals("Barney")) {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}

– Technically this is a method that returns a value of type boolean,


the type used in logical tests.

23
String test methods
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters,
ignoring upper vs. lower case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one

String name = console.next();


if (name.startsWith("Prof")) {
System.out.println("When are your office hours?");
} else if (name.equalsIgnoreCase("STUART")) {
System.out.println("Let's talk about meta!");
}

24
The for loop

25
Repetition with for loops
• So far, repeating a statement is redundant:
System.out.println("Homer says:");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("S-M-R-T... I mean S-M-A-R-T");

• Java's for loop statement performs a task many times.


System.out.println("Homer says:");
for (int i = 1; i <= 4; i++) { // repeat 4 times
System.out.println("I am so smart");
}
System.out.println("S-M-R-T... I mean S-M-A-R-T");

26
for loop syntax
for (initialization; test; update) {
header
statement;
statement;
... body
statement;
}

– Perform initialization once.


– Repeat the following:
• Check if the test is true. If not, stop.
• Execute the statements.
• Perform the update.
27
Initialization
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

• Tells Java what variable to use in the loop


– Performed once as the loop begins

– The variable is called a loop counter


• can use any name, not just i
• can start at any value, not just 1

28
Test
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

• Tests the loop counter variable against a limit


– Uses comparison operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to

29
Increment and decrement
shortcuts to increase or decrease a variable's value by 1

Shorthand Equivalent longer version


variable++; variable = variable + 1;
variable--; variable = variable - 1;

int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5

30
Modify-and-assign
shortcuts to modify a variable's value

Shorthand Equivalent longer version


variable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;
variable /= value; variable = variable / value;
variable %= value; variable = variable % value;

x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;

31
Repetition over a range
System.out.println("1 squared = " + 1 * 1);
System.out.println("2 squared = " + 2 * 2);
System.out.println("3 squared = " + 3 * 3);
System.out.println("4 squared = " + 4 * 4);
System.out.println("5 squared = " + 5 * 5);
System.out.println("6 squared = " + 6 * 6);
– Intuition: "I want to print a line for each number from 1 to 6"

• The for loop does exactly that!


for (int i = 1; i <= 6; i++) {
System.out.println(i + " squared = " + (i * i));
}

– "For each integer i from 1 through 6, print ..."


32
Loop walkthrough
1 2 3
for (int i = 1; i <= 4; i++) {
4 System.out.println(i + " squared = " + (i * i));
}
5 System.out.println("Whoo!");

1
Output:
1 squared = 1 2
2 squared = 4
3 squared = 9 4
4 squared = 16
Whoo!
3

33
Multi-line loop body
System.out.println("+----+");
for (int i = 1; i <= 3; i++) {
System.out.println("\\ /");
System.out.println("/ \\");
}
System.out.println("+----+");

– Output:
+----+
\ /
/ \
\ /
/ \
\ /
/ \
+----+
34
Expressions for counter
int highTemp = 5;
for (int i = -3; i <= highTemp / 2; i++) {
System.out.println(i * 1.8 + 32);
}
– Output:
26.6
28.4
30.2
32.0
33.8
35.6

35
System.out.print
• Prints without moving to a new line
– allows you to print partial messages on the same line

int highestTemp = 5;
for (int i = -3; i <= highestTemp / 2; i++) {
System.out.print((i * 1.8 + 32) + " ");
}

Output:
26.6 28.4 30.2 32.0 33.8 35.6

• Concatenate " " to separate the numbers

36
Counting down
• The update can use -- to make the loop count down.
– The test must say > instead of <

System.out.print("T-minus ");
for (int i = 10; i >= 1; i--){
System.out.print(i + ", ");
}
System.out.println("blastoff!");
System.out.println("The end.");

Output:
T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!
The end.

37
Nested for loops

38
Nested loops
• nested loop: A loop placed inside another loop.
for (int i = 1; i <= 5; i++) { // outer for loop
for (int j = 1; j <= 10; j++) { // inner for loop
System.out.print("*");
}
System.out.println(); // to end the line
}
• Output:
**********
**********
**********
**********
**********

• The outer loop repeats 5 times; the inner one 10 times.


– "sets and reps" exercise analogy
39
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}

• Output:
*
**
***
****
*****

5 lines 40
• Another way of triangle pattern

int stars=5;
for(int i=1;i<=5;i++) {
for(int j=1;j<=stars;j++)
{
System.out.print("*");
}
System.out.println();
stars--;
}

41
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}

• Output:
1
22
333
4444
55555

42
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5-(i-1); j++) {
System.out.print(5-(i-1));
}
System.out.println();
}

• Output:
55555
4444
333
22
1

43
Nested for loop exercise
• What is the output of the following nested for loops?
int num=5;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <=num; j++) {
System.out.print(num);
}
num--;
System.out.println();
}

• Output:
55555
4444
333
22
1 44
Common errors
• Both of the following sets of code produce infinite loops:
for (int i = 1; i <= 5; i++) {
for (int j = 1; i <= 10; j++) {
System.out.print("*");
}
System.out.println();
}

for (int i = 1; i <= 5; i++) {


for (int j = 1; j <= 10; i++) {
System.out.print("*");
}
System.out.println();
}

45
Complex lines
• What nested for loops produce the following output?
inner loop (repeated characters on each line)

....1
...2
..3 outer loop (loops 5 times because there are 5 lines)
.4
5

• We must build multiple complex lines of output using:


– an outer "vertical" loop for each of the lines
– inner "horizontal" loop(s) for the patterns within each line

46
Outer and inner loop
• First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}

• Now look at the line contents. Each line has a pattern:


– some dots (0 dots on the last line), then a number
....1
...2
..3
.4
5

– Observation: the number of dots is related to the line number. 47


Mapping loops to numbers
for (int count = 1; count <= 5; count++) {
System.out.print( ... );
}

– What statement in the body would cause the loop to print:


4 7 10 13 16

for (int count = 1; count <= 5; count++) {


System.out.print(3 * count + 1 + " ");
}
Count=1 4
Count=2 7
Count=3 10 48
Loop tables
• What statement in the body would cause the loop to print:
2 7 12 17 22

• To see patterns, make a table of count and the numbers.


– Each time count goes up by 1, the number should go up by 5.
– But count * 5 is too great by 3, so we subtract 3.

count number to print 5 * count 5 * count - 3


1 2 5 2
2 7 10 7
3 12 15 12
4 17 20 17
5 22 25 22

49
İnt num=2;
For(int count=1;count<=5;count++)
{System.out.print(num + " ");
num=num+5;
}

2 7 12 17 22

50
Loop tables question
• What statement in the body would cause the loop to print:
17 13 9 5 1

• Let's create the loop table together.


– Each time count goes up 1, the number printed should ...
– But this multiple is off by a margin of ...
count number to print -4 * count -4 * count + 21
1 17 -4 17
2 13 -8 13
3 9 -12 9
4 5 -16 5
5 1 -20 1

51
Nested for loop exercise
• Make a table to represent any patterns on each line.
....1 line # of dots -1 * line -1 * line + 5
...2
1 4 -1 4
..3
2 3 -2 3
.4
3 2 -3 2
5
4 1 -4 1
5 0 -5 0

• To print a character multiple times, use a for loop.


for (int j = 1; j <= 4; j++) {
System.out.print("."); // 4 dots
}
52
Nested for loop solution
• Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.println(line);
}

• Output:
....1
...2
..3
.4
5

53
Nested for loop exercise
• Answer:
....1
...22
..333
.4444
55555

Line 1 → 4 dots 1 times 1


Line 2→ 3 dots 2 times 2
Line 3→ 2 dots 3 times 3
Line 4→ 1 dot 4 times 4
Line 5→ 0 dot 5 times 5

54
Nested for loop exercise
• Answer:
. . . . .
. . . .
. . .
. .
.

1
22
333
4444
55555

55
Nested for loop exercise
• What is the output of the following nested for loops?
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
for (int k = 1; k <= line; k++) {
System.out.print(line);
}
System.out.println();
}
• Answer:
....1
...22
..333
.4444
55555 56
Nested for loop exercise
• Modify the previous code to produce this output:
....1
...2.
..3..
.4...
5....

• Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.print(line);
for (int j = 1; j <= (line - 1); j++) {
System.out.print(".");
}
System.out.println();
} 57
Drawing complex figures
• Use nested for loops to produce the following output.

#================#
| <><> |
| <>....<> |
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
58
Development strategy
• Recommendations for managing complexity:
1. Design the program (think about steps or methods needed).
• write an English description of steps required
• use this description to decide the methods
#================#
2. Create a table of patterns of characters | <><> |
• use table to write your for loops | <>....<> |
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
59
1. Pseudo-code
• pseudo-code: An English description of an algorithm.

• Example: Drawing a 12 wide by 7 tall box of stars


print 12 stars.
for (each of 5 lines) {
print a star. ************
* *
print 10 spaces. * *
print a star. * *
* *
} * *
print 12 stars. ************

60
Pseudo-code algorithm
1. Line
• # , 16 =, #

2. Top half
• |
• spaces (decreasing) #================#
• <>
| <><> |
• dots (increasing)
• <>
| <>....<> |
• spaces (same as above) | <>........<> |
• | |<>............<>|
|<>............<>|
3. Bottom half (top half upside-down) | <>........<> |
| <>....<> |
4. Line | <><> |
• # , 16 =, # #================#
61
Methods from pseudocode
public class Mirror {
public static void main(String[] args) {
line();
topHalf();
bottomHalf();
line();
}

public static void topHalf() {


for (int line = 1; line <= 4; line++) {
// contents of each line
}
}

public static void bottomHalf() {


for (int line = 1; line <= 4; line++) {
// contents of each line
}
}

public static void line() {


// ...
}
}
62
2. Tables
• A table for the top half:
– Compute spaces and dots expressions from line number

line spaces line * -2 + 8 dots 4 * line - 4

1 6 6 0 0 #================#
| <><> |
2 4 4 4 4
| <>....<> |
3 2 2 8 8 | <>........<> |
|<>............<>|
4 0 0 12 12
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
63
3. Writing the code
• Useful questions about the top half:
– What methods? (think structure and redundancy)
– Number of (nested) loops per line?

#================#
| <><> |
| <>....<> |
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
64
Partial solution
// Prints the expanding pattern of <> for the top half of the figure.
public static void topHalf() {
for (int line = 1; line <= 4; line++) {
System.out.print("|");
for (int space = 1; space <= (line * -2 + 8); space++) {
System.out.print(" ");
}
System.out.print("<>");
for (int dot = 1; dot <= (line * 4 - 4); dot++) {
System.out.print(".");
}
System.out.print("<>");
for (int space = 1; space <= (line * -2 + 8); space++) {
System.out.print(" ");
}
System.out.println("|");
}
}

65
Class constants
and scope

66
Scaling the mirror
• Let's modify our Mirror program so that it can scale.
– The current mirror (left) is at size 4; the right is at size 3.

• We'd like to structure the code so we can scale the figure by


changing the code in just one place.
#================# #============#
| <><> | | <><> |
| <>....<> | | <>....<> |
| <>........<> | |<>........<>|
|<>............<>| |<>........<>|
|<>............<>| | <>....<> |
| <>........<> | | <><> |
| <>....<> | #============#
| <><> |
#================#
67
Limitations of variables
• Idea: Make a variable to represent the size.
– Use the variable's value in the methods.

• Problem: A variable in one method can't be seen in others.


public static void main(String[] args) {
int size = 4;
topHalf();
printBottom();
}
public static void topHalf() {
for (int i = 1; i <= size; i++) { // ERROR: size not found
...
}
}
public static void bottomHalf() {
for (int i = size; i >= 1; i--) { // ERROR: size not found
...
}
}

68
Scope
• scope: The part of a program where a variable exists.
– From its declaration to the end of the { } braces
• A variable declared in a for loop exists only in that loop.
• A variable declared in a method exists only in that method.

public static void example() {


int x = 3;
i's scope

for (int i = 1; i <= 10; i++) {


System.out.println(x); x's scope
}
// i no longer exists here
} // x ceases to exist here

69
Scope implications
• Variables without overlapping scope can have same name.
for (int i = 1; i <= 100; i++) {
System.out.print("/");
}
for (int i = 1; i <= 100; i++) { // OK
System.out.print("\\");
}
int i = 5;
// OK: outside of loop's scope

• A variable can't be declared twice or used out of its scope.


for (int i = 1; i <= 100 * line; i++) {
int i = 2; // ERROR: overlapping scope
System.out.print("/");
}
i = 4; // ERROR: outside scope

70
Class constants
• class constant: A fixed value visible to the whole program.
– value can be set only at declaration; cannot be reassigned

• Syntax:
public static final type name = value;
– name is usually in ALL_UPPER_CASE

– Examples:
public static final int DAYS_IN_WEEK = 7;
public static final double INTEREST_RATE = 3.5;
public static final int SSN = 658234569;

71
Constants and figures
• Consider the task of drawing the following scalable figure:
+/\/\/\/\/\/\/\/\/\/\+
| |
| |
| | Multiples of 5 occur many times
| |
| |
+/\/\/\/\/\/\/\/\/\/\+

+/\/\/\/\+
| |
| | The same figure at size 2
+/\/\/\/\+

72
Repetitive figure code
public class Sign {
public static void main(String[] args) {
drawLine();
drawBody();
drawLine();
}
public static void drawLine() {
System.out.print("+");
for (int i = 1; i <= 10; i++) {
System.out.print("/\\");
}
System.out.println("+");
}
public static void drawBody() {
for (int line = 1; line <= 5; line++) {
System.out.print("|");
for (int spaces = 1; spaces <= 20; spaces++) {
System.out.print(" ");
}
System.out.println("|");
}
}
}
73
Adding a constant
public class Sign {
public static final int HEIGHT = 5;

public static void main(String[] args) {


drawLine();
drawBody();
drawLine();
}
public static void drawLine() {
System.out.print("+");
for (int i = 1; i <= HEIGHT * 2; i++) {
System.out.print("/\\");
}
System.out.println("+");
}
public static void drawBody() {
for (int line = 1; line <= HEIGHT; line++) {
System.out.print("|");
for (int spaces = 1; spaces <= HEIGHT * 4; spaces++) {
System.out.print(" ");
}
System.out.println("|");
}
}
} 74
Complex figure w/ constant
• Modify the Mirror code to be resizable using a constant.

A mirror of size 4: A mirror of size 3:


#================# #============#
| <><> | | <><> |
| <>....<> | | <>....<> |
| <>........<> | |<>........<>|
|<>........<>|
|<>............<>|
| <>....<> |
|<>............<>|
| <><> |
| <>........<> | #============#
| <>....<> |
| <><> |
#================#

75
Using a constant
• Constant allows many methods to refer to same value:
public static final int SIZE = 4;
public static void main(String[] args) {
topHalf();
printBottom();
}
public static void topHalf() {
for (int i = 1; i <= SIZE; i++) { // OK
...
}
}
public static void bottomHalf() {
for (int i = SIZE; i >= 1; i--) { // OK
...
}
}

76
Loop tables and constant
• Let's modify our loop table to use SIZE
– This can change the amount added in the loop expression
SIZE line spaces -2*line + (2*SIZE) dots 4*line - 4
4 1,2,3,4 6,4,2,0 -2*line + 8 0,4,8,12 4*line - 4
3 1,2,3 4,2,0 -2*line + 6 0,4,8 4*line - 4

#================# #============#
| <><> | | <><> |
| <>....<> | | <>....<> |
| <>........<> | |<>........<>|
|<>............<>| |<>........<>|
|<>............<>| | <>....<> |
| <>........<> | | <><> |
| <>....<> | #============#
| <><> |
77
#================#
Partial solution
public static final int SIZE = 4;
// Prints the expanding pattern of <> for the top half of the figure.
public static void topHalf() {
for (int line = 1; line <= SIZE; line++) {
System.out.print("|");
for (int space = 1; space <= (line * -2 + (2*SIZE)); space++) {
System.out.print(" ");
}
System.out.print("<>");
for (int dot = 1; dot <= (line * 4 - 4); dot++) {
System.out.print(".");
}
System.out.print("<>");
for (int space = 1; space <= (line * -2 + (2*SIZE)); space++) {
System.out.print(" ");
}
System.out.println("|");
}
}

78
Observations about constant
• The constant can change the "intercept" in an expression.
– Usually the "slope" is unchanged.
public static final int SIZE = 4;

for (int space = 1; space <= (line * -2 + (2 * SIZE));


space++) {
System.out.print(" ");
}

• It doesn't replace every occurrence of the original value.


for (int dot = 1; dot <= (line * 4 - 4); dot++) {
System.out.print(".");
}

79

You might also like