Lecture9 2024
Lecture9 2024
SCIENCE
CSI141
PROGRAMMING
h t t p : ht t p : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l
PRINCIPLES
Object Oriented Programming T ALLMAN NKGAU
R EPETITION
‣ Repetition – while, do-while, for
‣ File reading and writing
‣ Comparing Strings
‣ Nesting loops
http:http://horstmann.com/bjlo/index.html
Object Oriented Programming T ALLMAN NKGAU
A CKNOWLEDGEMENT :
S LIDES’ THEME FROM
R OBERT S EDGEWICK | K EVIN W AYNE
http:http://horstmann.com/bjlo/index.html
REPETITION
‣ Repetition
h t t p : ht t p : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l
Pause…
𝑥 𝑥 2 𝑥 3 𝑥 𝑁
1 + + + + ⋯+ , −∞ < 𝑥 < ∞
1! 2! 3! 𝑁!
5
Repetition: the while loop
▪ Repeat a block of code while a condition is true.
▪ If condition is false, continue with the next following
statement
int i = 0;
SYNTAX int v = 1;
int N = in.nextInt();
while (booleanExpression) while ( i <= N ) {
Statement_block; System.out.printf(“%d\n”, v);
i = i + 1;
Loop control variable v = 2 * v;
}
true false
i <= N?
7
Repetition: the while loop
❑ Write a Java program to compute
2 3 𝑁
𝑥 𝑥 𝑥 𝑥
1 + + + + ⋯+ , −∞ < 𝑥 < ∞
1! 2! 3! 𝑁!
int i = 0;
double sum = 0.0;
int N = in.nextInt();
double x = in.nextDouble();
while ( i <= N ) {
sum = sum + Math.pow(x, i) / Math.factorial(i);
i = i + 1;
}
System.out.printf(“sum = %.2f\n”, sum);
if (s.charAt(i) == ‘a’) {
count++;
What am I doing?
}
i = i + 1;
} 9
Repetition: the while loop – flag controlled
▪ Used to execute code until a Boolean variable is false
▪ For example, in data validation
boolean flag = false;
Must read a value > 0 int val = in.nextInt();
flag = val > 0;
while ( !flag ) {
⋮
System.out.printf(“Input int> 0: \n”);
val = in.nextInt();
flag = val > 0;
}
boolean flag = false;
int choice = in.nextInt();
Update flag - loop control variable
flag = choice == 1 || choice == 2;
while ( !flag ) {
System.out.printf(“Input 1 or 2: \n”);
choice = in.nextInt(); What am I doing?
flag = choice == 1 || choice == 2;
}
System.out.printf(“choice = %d\n”, choice);
10
Comparing Strings
Strings are a bit ‘special’ in Java – they are objects
Do not use the == operator with Strings nor any other object
・ The following compares the locations of two strings, and not
their contents
if (string1.equals(string2)) ...
Lexicographical Order
To compare Strings in ‘dictionary’ order
・When compared using compareTo, string1 comes:
– Before string2 if
string1.compareTo(string2) < 0
– After string2 if
string1.compareTo(string2) > 0
– Equal to string2 if
string1.compareTo(string2) == 0
・Notes
– string1 and string2 are string objects
– All UPPERCASE letters come before lowercase – ASCII code
– ‘space’ comes before all other printable characters
– Digits (0-9) come before all letters
– See Appendix A for the Basic Latin Unicode (ASCII) table
Repetition: the while loop – sentinel controlled
▪ Used to “read data” continuously until a specified value is read.
▪ The specified value is called the sentinel Sentinel value
⋮
val = in.nextInt();
Check if = SENTINEL ⋮
int count = 0;
}
final String SENTINEL = “END”;
String s = in.next();
while ( !s.equals(SENTINEL) ) { Update val - loop control variable
if (s.length() % 2 == 1) {
count++;
What am I doing?
}
s = in.next();
} 13
Pause
Write a Java application, called NumberStats.java,
that reads 8000 integers and computes the
average, maximum, and minimum of the
numbers.
▪ The usual nextInt(), nextDouble(), next(), nextLine() (from the Scanner class)
❑ For checking if there is data to read in the file:
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
16
File Input – Sentinel controlled loop
❑ Write a Java program segment to read positive integers from a file
whose name is read from the keyboard and display their average to
standard output. Use -1 to indicate end of data.
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
public class Average {
public static void main(String[] args) throws IOException {
String fileName;
int sum=0 , counter=0 , number, sentinel = -1;
double average;
Scanner kBoard = new Scanner (System.in);
System.out.printf("Enter name of input file: ");
fileName = kBoard.next(); Data in File
Scanner input = new Scanner (new FileReader(filename)); 12
number = input.nextInt();
3
while (number != sentinel){
counter++; 7 15
sum = sum + number; 25
number = input.nextInt(); 16 30 50
} 101
average = (1.0 * sum) / counter; -1
System.out.printf("Average = %.2f\n “, average );
17
input.close(); }}
File Input – end-of-file controlled loop
❑ Write a Java program segment to read positive integers from a file
whose name is read from the keyboard and display their average to
standard output.
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
public class Average {
public static void main(String[] args) throws IOException {
String fileName;
int sum=0 , counter=0 , number;
double average;
Scanner kBoard = new Scanner (System.in);
System.out.printf("Enter name of input file: ");
fileName = kBoard.next(); Data in File
Scanner input = new Scanner (new FileReader(filename)); 12
//number = input.nextInt();
3
while (input.hasNextInt()){
number = input.nextInt(); 7 15
counter++; 25
sum = sum + number; 16 30 50
} 101
average = (1.0 * sum) / counter;
System.out.printf("Average = %.2f\n “, average );
18
input.close(); }}
File Output
File Output
❑ MUST first open a file for writing:
String
Useful methods for file output
❑ For writing the file:
▪ The usual printf, print, println, close(), flush() (from the Scanner class)
❑ Note:
▪ If the file exists, it will be over-written. Otherwise it is created
▪ Always close the file.
19
File Output
Required imports for file output
import java.io.PrintWriter;
import java.io.IOException;
20
File Output
❑ Write a Java program segment to roll two dice 1000 times and write
to a file called gamble.dat the result of each roll – per line. Name of
output file is read from the keyboard.
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Random;
public class RollDice {
public static void main(String[] args) throws IOException {
String fileName; final int N = 1000;
int die1, die2, int i = 0;
Scanner in = new Scanner (System.in);
System.out.printf("Enter name of output file: ");
fileName = in.next(); Data in File
PrintWriter pw = new PrintWriter(fileName); 2 5
Random ran = new Random(12345);
4 1
while (i <= N){
die1 = ran.nextInt(6) + 1; die2 = ran.nextInt(6) + 1; 2 5
pw.printf(“%d %d\n”, die1, die2); 2 1
} 2 4
pw.close(); . . .
}
}
21
Input validation – Take 1
❑ Write a Java program to read a number
between 1 and 100. If the user enters a
number outside the range, keep asking until
they do. (Input validation)
System.out.printf(“Enter an int [1-100]: ”);
int N = in.nextInt();
while ( !((N >= 1) && (N <= 100))) {
System.out.printf(“Enter an int [1-100]: ”);
N = in.nextInt();
}
System.out.printf(“N = %d\n”, N);
22
Input validation – Take 2
❑ Write a Java program to read a number
between 1 and 100. If the user enters a
number outside the range, keep asking until
they do. (Input validation)
do {
System.out.printf(“Enter an int [1-100]: ”);
N = in.nextInt();
}
while (( !((N >= 1) && (N <= 100))) );
System.out.printf(“N = %d\n”, N);
true
int p = 1;
for ( int i = 0; i <= N; i++ ) {
System.out.printf(“%d %d\n”, i, p);
p = p * 2;
}
25
Flowchart
int p = 1;
int p = 1;
for ( int i = 0; i <= N; i++) {
System.out.printf(“%d %d\n”, i, p);
p = p * 2;
}
int i = 0; initialization
true false
i <= N?
Statement
i++; update after body
of loop
26
Every for loop is a while loop
Use a for loop when
• Counting integrally
• Increment/decrement steps are constant
• Counting limits are known
int p = 1;
for ( int i = 0; i <= N; i++) {
System.out.printf(“%d %d\n”, i, p);
p = p * 2;
}
int p = 1;
int i = 0; // initialization come before while
while ( i <= N ) { // Boolean expression here
System.out.printf(“%d %d\n”, i, p);
p = p * 2;
i++; // update at the end of for loop body
}
27
Pop quiz
Question. What is displayed by the following code?
28
Nested loops
int N = 3;
int sum = 0;
for (int i = 1; i < N; i++) {
int j = 0;
while ( j <= i) {
sum = sum + j;
j++;
}
}
System.out.printf(“sum = %d\n”, sum);
A. sum = 4
29
Your turn
N = 5
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
30
Your turn
N = 5
*****
****
***
**
*
31
Your turn
N = 5
*****
****
***
**
*
32
Summary
33
Object Oriented Programming T ALLMAN NKGAU
JAVA REVIEW
http:http://horstmann.com/bjlo/index.html