JAVA Week 4 and 5
JAVA Week 4 and 5
Chapter 5
Program Logic and Indefinite Loops
2
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'
– What is s + 1 ? What is c + 1 ?
– What is s + s ? What is c + c ?
3
The equals method
• Objects are compared using a method named equals()
Scanner console = new Scanner(System.in);
– What is == for?
4
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
5
while loops
6
Categories of loops
• definite loop: Executes a known number of times.
– The for loops we have seen are definite loops.
• Print "hello" 10 times.
• Find all the prime numbers up to an integer n.
• Print each odd number between 5 and 127.
7
Example while loop
// sum positive integers entered by the user
int uNum = 0;
int total = 0;
while(uNum >=0)
{
total = total+uNum;
System.out.println(“Enter a number to add,
negative number to exit”);
uNum = console.nextInt();
}
System.out.println(“The total is: " + total);
8
Sentinel values
• sentinel: A value that signals the end of user input.
9
Sentinel solution
• What's wrong with this solution?
Scanner console = new Scanner(System.in);
int sum = 0;
int number = 1; // "dummy value", anything but 0
while (number != 0) {
System.out.print("Enter a number (0 to quit): ");
number = console.nextInt();
sum = sum + number;
}
10
Sentinel as a constant
public static final int END_NUM = -1;
...
Scanner console = new Scanner(System.in);
int sum = 0;
11
Other Loop
Options/Settings
• break; is like a stop sign in a loop
12
Math with Return
Values
14
Calling Math methods
Math.methodName(parameters)
• Examples:
double squareRoot = Math.sqrt(121.0);
System.out.println(squareRoot); // 11.0
System.out.println(Math.min(3, 7) + 2); // 5
15
Random numbers
– Example:
Random rand = new Random();
int randomNumber = rand.nextInt(10); // 0-9
17
Generating random
numbers
• Common usage: to get a random number from 1 to N
int n = rand.nextInt(20) + 1; // 1-20 inclusive
int n = rand.nextInt(7) + 4; 18
Random question
• Write a program that simulates rolling of two 6-sided
dice until their combined result comes up as 7.
2 + 4 = 6
3 + 5 = 8
5 + 6 = 11
1 + 1 = 2
4 + 3 = 7
You won after 5 tries!
19
Random answer
// Rolls two dice until a sum of 7 is reached.
import java.util.*;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int tries = 0;
int sum = 0;
while (sum != 7) {
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
}
System.out.println("You won after " + tries + " tries!");
}
}
20
The do/while loop
• do/while loop: Performs its test at the end of each
repetition.
– Guarantees that the loop's {} body will run at least once.
do {
statement(s);
} while (test);
22
Type boolean
Efficient!
True/False
Methods that are tests
• Some methods return logical values.
– A call to such a method is used as a test in a loop or if.
if (name.startsWith("Dr.")) {
System.out.println(“Can you look at my knee?");
} else if (name.endsWith("Esq.")) {
System.out.println(“Please don’t sue me!");
}
24
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
26
Using boolean
• Why is type boolean useful?
– Can capture a complex logical test result and use it later
– Can write a method that does a complex test and returns
it
– Makes code more readable
– Can pass around the result of a logical test (as
param/return)
31
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
32
printf width
– %Wd digit, W characters wide, right-aligned
– %-Wd digit, W characters wide, left-aligned
– %Wf floating point num, 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
33
printf precision
– %.Df float, rounded to D digits after decimal
– %W.Df float, W chars wide, D digits after decimal
– %-W.Df float, W wide (left-align), D after decimal
Output:
your GPA is 3.3 3
34