More Iteration Structures

definite loop: a loop that executes a known number of times.
•  for loops are definite loops - it's obvious typically how many times a for loop's body will be executed.
• Example: for(int i = 1; i <= 10; i++) {...} // do something 10 times

indefinite loop: a loop that does not execute a known number of times. Instead, an indefinite loop executes until some condition is satisfied.
• while loops and do-while loops are the indefinite loop structures that we will study
• Examples: tasks that call for an indefinite loop
• while the user's input is not a positive integer, prompt for and read another input value
• while it's not true that the user entered the same password twice in a row, read the password again

The while statement

Example:
while(you are hungry)
{
eat another bite
}

Example:
while(there are more lines of text in the input file)
{
read the next line from the file
}

Syntax:
while(<condition>)
{
<statement(s)>
}

How it works:
A while statement executes a block of code repeatedly, as long as the <condition> is true. The condition is evaluated before each execution of the statements in the loop body, and if the condition evalutes to false, execution of the while loop terminates.

Example:
int count = 1;
while(count <= 5)
{
count++;
}
System.out.println("count is " + count);

Example:
int num = 1;
int sum = 0;

// add nums from 1 to 5 to sum
while(num <= 5)
{
sum = sum + num;
num++;  // what happens if I omit this??
}
System.out.println("The sum of the first 5 positive integers is " + sum);

Question: Consider the following code:
int x = 5;
int y = 13;
while (x < y) {
System.out.println("loop-di-loop");
x += 2;
y -= 2;
}

How many times is the phrase "loop-di-loop" printed?
A.  1
B. 2
C. 3
D. 4
E. 5

Practice with while loops

Exercise: Write a while loop that prints the squares of the integers from 1 to 15 to the console window, separated by spaces.

Exercise: Prompt the user to enter a sequence of positive integers, one at a time. The user enters zero or a negative number to quit. Print the sum of the positive integers.

Sentinel Loops

Our last exercise is an example of a loop called a sentinel loop:
The loop gets and processes values until seeing a special value called the sentinel, that indicates that processing should stop.

Note: In the above exercise, the sentinel is either 0 or a negative number.

In general, the psuedo-code for a sentinel loop is like this:

while value is not the sentinel:
process the value

Example: Write a program that prompts the user for input until a positive integer is entered. Once a positive integer is entered, the program should print the square of that integer. For now, we will assume that all values entered by the user are integers.

Sample Output:
Enter a positive integer: -44
Not a valid input. Positive integer, please: 0
Not a valid input. Positive integer, please: 5
The square of 5 is 25.

for and while Loop Example

Consider this for loop:
for(int i = 1; i <= 10; i++)
{
System.out.println(i*i);
}

What is an equivalent while loop?

int i = 1;
while(i <= 10)
{
System.out.println(i*i);
i++;
}

while Loops and for Loops

• Every for loop has an equivalent while loop that performs the exact same action.

for(<init>; <condition>; <update>)
{
<body statement(s)>
}

Equivalent while loop:

<init>;
while(<condition>)
{
<body statement(s)>
<update>;
}

Review Question

Consider the following for loop:

for(int i = 2; i <= 20; i+=3)
System.out.println(i);

Which while loop below is equivalent?

A.                                                      B.
int i = 2;                                            int i = 2;
i += 3;                                               while(i <= 20) {
while(i <= 20) {                                     i+= 3;
System.out.println(i);                           System.out.println(i);
i += 3;                                            }
}

C.                                                      D. A and B
int i = 2;
while(i <= 20) {                                E. A, B and C.
System.out.println(i);
}
i += 3;

Testing Validity of User Input

• The Scanner class contains methods that allow us to test the type of the next token before we attempt to read it using next(), nextInt(), nextDouble(), etc.
• These methods allow us to deal with user errors without crashing our program!
• All of these methods wait for the user to enter the token and hit <enter> before returning.

 Method Description hasNext() returns true if there's another token that can be read as a String (only useful for file input - more on this later) hasNextInt() returns true if next token can be read as an int hasNextDouble() returns true if next token can be read as a double hasNextLine() returns true if there's another line of input that can be read as a String (only useful for file input)

Example: Write a program that asks the user for 10 numbers, and then prints a message indicating whether each is an integer or a floating-point number.

System.out.print("Enter 10 numbers: ");
for(int i = 1; i <= 10; i++)
{
System.out.println(reader.nextInt() + ": is an integer");
else
System.out.println(reader.nextDouble() + ": is a floating point number");
}

The do-while statement

Like a while loop, except the loop body is always executed once.

Syntax:
do
{
<statement(s)>
}
while (<condition>) ;

How it works:
• The body of the loop is executed, and then the condition is evaluated.
• If the condition is true, the body is executed, and this process repeats.

Psuedo-code Example:
do
{
start the car's engine
}
while(engine is not running);

Example:

int val = 5;

// what does this loop do?
do
{
System.out.println(val);
val--;
}
while(val> 1);

Review Question

Consider the do while loop below:

do {
y = x+5;
x = x+1;
} while(x < 8);

Which code below is equivalent?

A.                                  B.
y = x+5;                            while(x < 8) {
x++;                                      y = x+5;
while (x < 8) {                       x = x+1;
y = x+5;                          }
x++;                                y = x+5;
}                                         x = x+1;

C.                                  D. A and B
while(x < 8) {
y = x+5;                    E. A, B and C
x++;
}

Practice Problems

Exercise: Write a program that reads integers from the user until the user enters 0. Then the program prints the number of positive integers and the number of negative integers that were entered.

Exercise: Write a method that takes two integer arguments, and returns true if both arguments are positive and false otherwise.

Exercise: Write a program that reads numbers from the user until the user enters "stop" (regardless of case). When the user enters "stop", print the sum of the numbers.

Exercise - Random class review: Write a few lines of Java code that print:
a) a random integer 0 to 20
b) a random integer 2 to 5
c) a random integer -10 to 10
d) a random even integer from 2 to 18

Exercise: Convert the following for loop to a while loop:
double sum = 0;
for(int i = 0; i <= 1000; i++)
sum = sum + i;

Exercise: Write a program that prompts the user to enter positive integers (or 0 or a negative number to stop). Print the largest positive integer that was entered. (What is the sentinel??)

Converting Strings to Numeric Types

Two Static Methods:
• Integer.parseInt(String s): If s is the string representation of an integer, that integer is returned
• Double.parseDouble(String s): If s is the string representation of a floating point number, that floating point number is returned

Example:
String str = "14.3";
double strDouble = Double.parseDouble(str); // 14.3

Example:
String myString = "123";
int myInt = Integer.parseInt(myString); // myInt is 123