L7 - Formatted Output and IndefiniteLoop
L7 - Formatted Output and IndefiniteLoop
– 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
– ...
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
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.
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
}
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
}
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.
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
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));
}
}
16
sentinel code solution
Scanner console = new Scanner(System.in);
int sum = 0;
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.
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);
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);
• 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;
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
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