Lecture 6
Lecture 6
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 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-
4
Cumulative algorithms
Adding many numbers
• How would you find the sum of all integers from 1-1000?
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);
8
Scanner and cumul. sum
• We can do a cumulative sum of user input:
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
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
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.");
}
14
char vs. int
• Each char is mapped to an integer value internally
– Called an ASCII value
15
char vs. String
• "h" is a String, but 'h' is a char (they are different)
16
Formatting text with printf
System.out.printf("format string", parameters);
– 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
– ...
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
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 .
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.
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!");
}
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
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");
26
for loop syntax
for (initialization; test; update) {
header
statement;
statement;
... body
statement;
}
28
Test
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}
29
Increment and decrement
shortcuts to increase or decrease a variable's value by 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
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"
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
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:
**********
**********
**********
**********
**********
• 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();
}
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
46
Outer and inner loop
• First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}
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
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
• Output:
....1
...2
..3
.4
5
53
Nested for loop exercise
• Answer:
....1
...22
..333
.4444
55555
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.
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();
}
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.
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.
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
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;
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;
79