0% found this document useful (0 votes)
13 views34 pages

Lecture9 2024

The document provides an overview of programming concepts in Java, focusing on object-oriented programming principles, particularly repetition using loops such as while, do-while, and for. It includes examples of input validation, file reading and writing, and string comparison, along with practical exercises for writing Java programs. The content is structured to guide users through understanding and implementing these programming concepts effectively.

Uploaded by

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

Lecture9 2024

The document provides an overview of programming concepts in Java, focusing on object-oriented programming principles, particularly repetition using loops such as while, do-while, and for. It includes examples of input validation, file reading and writing, and string comparison, along with practical exercises for writing Java programs. The content is structured to guide users through understanding and implementing these programming concepts effectively.

Uploaded by

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

COMPUTER

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…

❑ Write a Java program to compute

𝑥 𝑥 2 𝑥 3 𝑥 𝑁
1 + + + + ⋯+ , −∞ < 𝑥 < ∞
1! 2! 3! 𝑁!

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

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

Updating the loop control variable

❑Boolean expression should eventually evaluate to false


❑Some variables are used as loop control variables – they get
updated in the code block and eventually make the Boolean
expression false
6
Flowchart - while true do pattern
int p = 1;
int p = 1;
Int i = 0;
while( i <= N ) {
System.out.printf(“%d %d\n”, i, p);
p = p * 2;
i++;
}
p = p + 2 * i;
int i = 0; initialization

true false
i <= N?

while loop body

System.out.printf(“%d %d\n”, i, p);


p = p * 2;
i++; update Statement after
body of loop:
p = p + 2 * i;

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

Note: Math.factorial() DOES NOT exist! and 0! = 1


8
Repetition: the while loop - counting
▪ Starting with an initial value v.
▪ Stop when v >= N
int i = 0;
int N = in.nextInt();
while ( i <= N ) {
counting variable

i = i + 2;
Check if <= N ⋮
int i = 0; int count = 0;
String s = “Skate Away”; }
int N = s.length();
while ( i < N ) { Increment counting variable

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 == string2) ...

Instead use the String’s equals method:

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

final int SENTINEL = -1;


Must read first value outside
loop
int val = in.nextInt();
while ( val != SENTINEL ) {


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.

Hint. Do this with a while loop like the following


int N = 10, i = 1;
while (i <= N) {
prompt for a number;
read number;
process number;
i++;
}
File Input
❑ MUST first open a file for reading:
FileReader varName1 = new FileReader(fName);

then Scannerize the file:


String

Scanner varName2 = new Scanner(varName1);

❑ The above two can be done in one step as follows:


Scanner varName = new Scanner(new FileReader(fName));
Useful methods for file input
❑ For reading from the file:

▪ The usual nextInt(), nextDouble(), next(), nextLine() (from the Scanner class)
❑ For checking if there is data to read in the file:

▪ hasNext(), hasNextInt(), hasNextDouble(), hasNextLine() (all boolean methods)


❑ Note:
▪ Ensure that the file you want to read from exists!
▪ Always close the file. 15
File Input
Required imports for file input

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:

PrintWriter varName1 = new PrintWriter(fName);

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

Note: loop body is executed at least once


23
Flowchart - do while true pattern
do {
System.out.printf(“Enter an int [1-100]:
”);
N = in.nextInt();
}
while (( !((N >= 1) && (N <= 100))) );
System.out.printf(“N = %d\n”, N);

System.out.printf(“%d %d\n”, i, p);


p = p * 2;
i++;

true

!((N >= 1) &&


(N <= 100)))
false

System.out.printf(“N = %d\n”, N);


24
Repetition – for loops
• Alternative repetition statement
• Syntactic sugar – its just a while loop!

int p = 1;
for ( int i = 0; i <= N; i++ ) {
System.out.printf(“%d %d\n”, i, p);
p = p * 2;
}

initialization Boolean expression Update statement

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?

For loop body

System.out.printf(“%d %d\n”, i, p);


p = p * 2;

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?

public class Loop {


public static void main(String[] args) {
int sum = 0;
int count = 0;
int N = 10;
for (int i = 1; i < N; i++) {
if (i % 2 == 1) { sum = sum + i; count++; }
}
System.out.printf(“i = %d, count = %d\n”, i, count);
}
}

Answer. Compile time error. Variable i not in scope.

28
Nested loops

Q. What is the output of this code?

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

Q. Write a Java program to read an integer N (between


1 and 15, inclusive) from the keyboard and display a
pattern like this.

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

Q. Write a Java program to read an integer N (between


1 and 10, inclusive) from the keyboard and display a
pattern like this.

N = 5

*****
****
***
**
*

31
Your turn

Q. Write a Java program to read an integer N (between


1 and 10, inclusive) from the keyboard and display a
pattern like this.

N = 5

*****
****
***
**
*

32
Summary

❑Repetition statements are used to execute a block of


statements based on the value of a Boolean expression

❑ Be familiar with the different while-loop patterns for solving


problems

❑Know when to use do-while, while-do, and for loops

❑ Watch out for infinite loops and borderline cases


.

33
Object Oriented Programming T ALLMAN NKGAU

JAVA REVIEW

‣ Nested while loops


‣ Repetition – for loops

http:http://horstmann.com/bjlo/index.html

You might also like