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

L7 - Formatted Output and IndefiniteLoop

The document covers various Java programming concepts including formatting output with printf, different types of loops (fencepost, while, do/while, and sentinel loops), and boolean operations. It provides examples of how to implement these concepts in code, emphasizing the importance of proper syntax and logic in programming. Additionally, it discusses methods for input validation using the Scanner class and techniques for calculating sums and averages.

Uploaded by

thethingis618
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

L7 - Formatted Output and IndefiniteLoop

The document covers various Java programming concepts including formatting output with printf, different types of loops (fencepost, while, do/while, and sentinel loops), and boolean operations. It provides examples of how to implement these concepts in code, emphasizing the importance of proper syntax and logic in programming. Additionally, it discusses methods for input validation using the Scanner class and techniques for calculating sums and averages.

Uploaded by

thethingis618
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Building Java Programs

Formatting with printf,


Fencepost Loop, while/do wile
loops, boolean zen, sentinel
loop, more Scanner method
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

2
printf width
• %Wd integer, W characters wide, right-aligned
• %-Wd integer, W characters wide, left-aligned
• %Wf real number, 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
3
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

double gpa = 3.253764;


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

Output:
your GPA is 3.3 8
more precisely: 3.254
4
Building Java Programs

Fencepost Loop
A deceptive problem...
• Write a method printNumbers that prints each number
from 1 to a given maximum, separated by commas.

For example, the call:


printNumbers(5)

should print:
1, 2, 3, 4, 5

6
Flawed solutions
public static void printNumbers(int max) {
for (int i = 1; i <= max; i++) {
System.out.print(i + ", ");
}
System.out.println(); // to end the line of output
}

– Output from printNumbers(5): 1, 2, 3, 4, 5,

public static void printNumbers(int max) {


for (int i = 1; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line of output
}

– Output from printNumbers(5): , 1, 2, 3, 4, 5

7
Fencepost method
solution
public static void printNumbers(int max) {
System.out.print(1);
for (int i = 2; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
}

• Alternate solution: Either first or last "post" can be taken out:


public static void printNumbers(int max) {
for (int i = 1; i <= max - 1; i++) {
System.out.print(i + ", ");
}
System.out.println(max); // to end the line
}
8
while loops

9
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 types "q" to quit.

10
The while loop
• while loop: Repeatedly executes its
body as long as a logical test is true.
while (test) {
statement(s);
}

• Example:
int num = 1; // initialization
while (num <= 200) { // test
System.out.print(num + " ");
num = num * 2; // update
}
// output: 1 2 4 8 16 32 64 128
11
Example while loop
// finds the first factor of 91, other than 1
int n = 91;
int factor = 2;
while (n % factor != 0) {
factor++;
}
System.out.println("First factor is " + factor);
// output: First factor is 7

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


many times we will need to increment to find the factor.

12
Sqrt (by hand first)

13
Sqrt program

14
Variation of Sqrt program
public class Sum{
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter a positive number” +
” (negative or 0 to quit): ");
double n;
//read a number then check if it is > 0,
// if n<=0 don’t get into the loop
while ((n = console.nextDouble()) > 0){
System.out.printf("\nsqrt of %f is %f", n, sqrt(n));
}
}

//method to compute SQRT


public static double sqrt(double n){
double EPS = 1E-15; // 10^-15 to specify precisions
double t = n;

//repeat until (ti - n/ti)≈ 0 or EPS


//multiply EPS by n to reduce precision (useful for big numbers)
while (Math.abs(t – n / t) > n * EPS){
t = (t + n / t) / 2.0; //ti+1=(ti + n/ti)/2
}
return t;
}
} 15
Sentinel values
• sentinel: A value that signals the end of user input.
– sentinel loop: Repeats until a sentinel value is seen.

• Example: Write a program that prompts the user for


numbers until the user types -1, then outputs their
sum.
– (In this case, -1 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 (-1 to quit): -1
The sum is 60

16
sentinel code solution
Scanner console = new Scanner(System.in);
int sum = 0;

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


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

while (number != -1) {


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

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

17
"Forever" loop with break
• break statement: Immediately exits a loop.
– Can be used to write a loop whose test is in the middle.
– Such loops are often called "forever" loops because their
header's boolean test is often changed to a trivial true.

• "forever" loop, general syntax:


while (true) {
<statement(s)> ;

if (<condition>) {
break;
}
<statement(s)> ;
} 18
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")); 19
do/while question
• Rolls two dice until a sum of 7 is reached
2 + 4 = 6
3 + 5 = 8
5 + 6 = 11
1 + 1 = 2
4 + 3 = 7
You won after 5 tries!

• Is do/while a good fit for our past Sentinel program?

20
do/while answer
// Rolls two dice until a sum of 7 is reached.
public class Dice {
public static void main(String[] args) {
int tries = 0;
int sum;

do {
int roll1 = getRandom(6) ; // one roll
int roll2 = getRandom(6) ;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
tries++;
} while (sum != 7);

System.out.println("You won after " + tries + " tries!");


}

// returns random integer between 1 and n.


public static int getRandom(int n) {
return 1 + (int) (Math.random() * n);
}
} 21
Type boolean
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; return factors == 2;
} else {
return false;
}
}

• Calls to methods returning boolean can be used as tests:


if (isPrime(57)) {
...
}
23
Remark 1
• Students new to boolean often test if a result is true:
if (isPrime(57) == true) { // bad
...
}

• But this is unnecessary and redundant. Preferred:


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

• A similar pattern can be used for a false test:


if (isPrime(57) == false) { // bad
if (!isPrime(57)) { // good
24
Remark 2
• Replace
public static boolean name(parameters) {
if (test) {
return true;
} else {
return false;
}
}

• with
public static boolean name(parameters) {
return test;
}

25
Improved isPrime method
• The following version utilizes Boolean Zen:
public static boolean isPrime(int n) {
int factors = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
factors++;
}
}
return factors == 2; // if n has 2 factors, true
}

26
Efficient isPrime method
/**
*
* @param n
* @return true if n is prime, false otherwise.
*/
public static boolean isPrime(int n) {
if(n <= 1)
return false;

int maxPossibleFactor = 1 + (int) Math.sqrt(n);

for(int i = 2; i <= maxPossibleFactor; i++)


if(n%i == 0) return false;

return true;
}

27
De Morgan's Law
• De Morgan's Law: Rules used to negate boolean
tests.
– Useful when you want the opposite of an existing test.
Original Negated Alternativ
Expression Expression e
a && b !a || !b !(a && b)
a || b !a && !b !(a || b)

– Example:
Original Code Negated Code
if (x == 7 && y > 3) { if (x != 7 || y <= 3) {
... ...
} }

28
Scanner
Testing for Valid Input
• Scanner methods to see what the next token will be:
Method Description
hasNext() returns true if there are any more tokens
of input to read.
hasNextInt() returns true if there is a next token
and it can be read as an int
hasNextDouble() returns true if there is a next token
and it can be read as a double

• These methods do not consume input;


they just give information about the next token.
– Useful to see what input is coming, and to avoid crashes.
• <Ctrl-d> is OS X/LINUX/UNIX EOF
• <Ctrl-z> is Windows analog. 29
Averaging a stream of
intergers

30
Averaging a stream of
intergers
public class Sum{
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int sum =0;
System.out.println("Enter a number (-1 TO QUIT)= ");
int number = readInt(console);
while (number != -1){
sum += number;
System.out.println("Enter a number (-1 TO QUIT)= ");
number = readInt(console);
}
System.out.printf("\nThe sum od numbers is = %d", sum);
}
//method will block until it reads an integer
public static int readInt(Scanner input){
while (!input.hasNextInt()){
input.next(); //read and throw away non integers
}
return input.nextInt();
}

}
31

You might also like