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

JAVA Week 4 and 5

Chapter 5 of 'Building Java Programs' covers program logic and indefinite loops, explaining the differences between char and String types, the use of the equals method for object comparison, and various String test methods. It also introduces while loops, sentinel values, and the do/while loop, along with examples of generating random numbers using the Random class. Additionally, the chapter discusses boolean logic, short-circuit evaluation, and formatting text with printf.

Uploaded by

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

JAVA Week 4 and 5

Chapter 5 of 'Building Java Programs' covers program logic and indefinite loops, explaining the differences between char and String types, the use of the equals method for object comparison, and various String test methods. It also introduces while loops, sentinel values, and the do/while loop, along with examples of generating random numbers using the Random class. Additionally, the chapter discusses boolean logic, short-circuit evaluation, and formatting text with printf.

Uploaded by

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

Building Java Programs

Chapter 5
Program Logic and Indefinite Loops

Copyright (c) Pearson 2013.


All rights reserved.
char vs String

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'

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


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

– 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);

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!");
}

– What is == for?

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


the type used in logical tests.

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

String name = console.next();


if (name.startsWith("Prof")) {
System.out.println("When are your office hours?");
} else if (name.equalsIgnoreCase(“Dr")) {
System.out.println(“What did you study?");
}

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.

• indefinite loop: One where the number of times its


body repeats is not known in advance.
• Prompt the user until they type a non-negative number.
• Print random numbers until a prime number is printed.
• Repeat until the user has types "q" to quit.

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);

– while is better than for because we don't know how


many times the loop will iterate

8
Sentinel values
• sentinel: A value that signals the end of user input.

• Example: Write a program that prompts the user for


numbers until the user types 0, then outputs their sum.
– (In this case, 0 is the sentinel value.)

Enter a number (0 to quit): 10


Enter a number (0 to quit): 20
Enter a number (0 to quit): 30
Enter a number (0 to quit): 0
The sum is 60

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;
}

System.out.println("The total is " + sum);

10
Sentinel as a constant
public static final int END_NUM = -1;
...
Scanner console = new Scanner(System.in);
int sum = 0;

// pull one prompt/read ("post") out of the loop


System.out.print("Enter a number (" + END_NUM +
" to quit): ");
int number = console.nextInt();

while (number != END_NUM ) {


sum = sum + number; // moved to top of loop
System.out.print("Enter a number (" + END_NUM +
" to quit): ");
number = console.nextInt();
}

System.out.println("The total is " + sum);

11
Other Loop
Options/Settings
• break; is like a stop sign in a loop

• continue; is like a detour back to the top of the loop,


skip the rest of this iteration

• These can usually be avoided by using sentinel values


or other loop logic setups. They are fine to use, but are
a bit less readable

• Avoid the use of while(true) loops!

12
Math with Return
Values

Methods that have a result


Java's Math class

Method name Description Memorize this?


Math.abs(value) absolute value Y
Math.ceil(value) rounds up Y
Math.floor(value) rounds down Y
Math.log10(value) logarithm, base 10
Math.max(value1, larger of two values Y
value2)
Math.min(value1, smaller of two values Y
value2)
Math.pow(base, exp) base to the exp power Y
Math.random() random double between 0
and 1
Math.round(value) nearest whole number Y
Math.sqrt(value) square root
Math.sin(value) sine/cosine/tangent of Constant Description
Math.cos(value) an angle in radians Math.E 2.7182818...
Math.tan(value) Math.PI 3.1415926...

14
Calling Math methods
Math.methodName(parameters)

• Examples:
double squareRoot = Math.sqrt(121.0);
System.out.println(squareRoot); // 11.0

int absoluteValue = Math.abs(-50);


System.out.println(absoluteValue); // 50

System.out.println(Math.min(3, 7) + 2); // 5

• The Math methods do not print to the console.


– Each method produces ("returns") a numeric result.
– The results are used as expressions (printed, stored, etc.).

15
Random numbers

… and using the Random object


The Random class
• A Random object generates pseudo-random numbers.
– Class Random is found in the java.util package.
import java.util.*;
Method name Description
nextInt() returns a random integer
nextInt(max) returns a random integer in the range [0, max)
in other words, 0 to max-1 inclusive
nextDouble() returns a random real number in the range [0.0, 1.0)

– 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

• To get a number in arbitrary range [min, max]


inclusive:
name.nextInt(size of range) + min

• where (size of range) is (max - min + 1)

– Example: A random integer between 4 and 10 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);

// Example: prompt until correct password is typed


String phrase;
do {
System.out.print("Type your password: ");
phrase = console.next();
} while (!phrase.equals("abracadabra")); 21
do/while example

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.

Scanner console = new Scanner(System.in);


System.out.print("Type your first name: ");
String name = console.next();

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

String name = console.next();


if (name.contains("Prof")) {
System.out.println("When are your office hours?");
} else if (name.equalsIgnoreCase("STUART")) {
System.out.println("Let's talk about meta!");
}
25
Type boolean
• boolean: A logical type whose values are true and
false.
– A logical test is actually a boolean expression.

boolean minor = (age < 21);


boolean isProf = name.contains("Prof");
boolean lovesCSE = true;

// allow only CSE-loving students over 21


if (minor || isProf || !lovesCSE) {
System.out.println("Can't enter the club!");
}

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)

boolean goodAge = age >= 12 && age < 29;


boolean goodHeight = height >= 78 && height < 84;
boolean rich = salary >= 100000000.0;
if ((goodAge && goodHeight) || rich) {
System.out.println("Okay, let's go out!");
} else {
System.out.println("It's not you, it's me...");
}
27
Returning boolean
public static boolean isPrime(int n) {
int factors = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
factors++;
}
}
if (factors == 2) {
return true;
} else {
return false;
}
}

• Calls to methods returning boolean can be used as


tests:
if (isPrime(57)) {
...
} 28
Naming and using bool
• Students new to boolean often test if a result is true:
if (isPrime(57) == true) { // bad, ugly
...
}

• But this is unnecessary and redundant. Preferred:


if (isPrime(57)) { // good, simple
...
}

• Boolean data can/should be expressed as yes/no or


True/False
– hasItems, testPassed, isGood, needsTickets
29
"Short-circuit"
evaluation
• Java stops evaluating a test if it knows the answer.
– && stops early if any part of the test is false
– || stops early if any part of the test is true

• The following test will crash if s2's length is less than 2:


// Returns true if s1 and s2 end with the same two letters.
public static boolean rhyme(String s1, String s2) {
return s1.endsWith(s2.substring(s2.length() - 2)) &&
s1.length() >= 2 && s2.length() >= 2;
}

• The following test will not crash; it stops if length < 2:


// Returns true if s1 and s2 end with the same two letters.
public static boolean rhyme(String s1, String s2) {
return s1.length() >= 2 && s2.length() >= 2 &&
s1.endsWith(s2.substring(s2.length() - 2));
} 30
Printf – not on quiz, just FYI

Useful for $$ formatting

Not useful for much else, we rarely run command


line reports Printf
(not on quizzes, just FYI)

31
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

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

double gpa = 3.253764;


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

Output:
your GPA is 3.3 3

more precisely: 3.254


8

34

You might also like