More Iteration Structures

definite loop: a loop that executes a known number of times.

indefinite loop: a loop that does not execute a known number of times. Instead, an indefinite loop executes until some condition is satisfied.



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



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. 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:

read the first value
while value is not the sentinel:
     process the value
     read the next 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>;
}


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.

Scanner reader = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
for(int i = 1; i <= 10; i++)
{
    if(reader.hasNextInt())
       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.



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




Practice Problems



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.


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


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.


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

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


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.


Converting Strings to Numeric Types

Two Static Methods:

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

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