While Loop

Objective:

In this lab, we will demonstrate how to use the while loop. We will also look into the advanced Java classes that we will study in later lectures.

By the end of this lab, learners will be able to use while loop in java

While loop Overview

A while loop will continually process a statement or given code block while its evaluation expression is true.

while (condition) {
    statement(s)
}

Example #1: Guess the Number

Write a program that randomly generates an integer between 0 and 100, inclusive. The program should prompt the user to enter a number repeatedly until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high. When the user discovers the correct answer, the program outputs a congratulatory message, and then provides the user with the opportunity to play again.

Solution: Guess the Number

Make a new class named GuesstheNumber. Inside, write the code shown below.

import java.util.Scanner;
public class GuesstheNumber {
   public static void main(String[] args) {
       // Generate a random number to be guessed
       int number = (int) (Math.random() * 101);
       Scanner input = new Scanner(System.in);
       System.out.println("Guess a magic number between 0 and 100");
       int guess = -1;
       while (guess != number) {
           // Prompt the user to guess the number
           System.out.print("\\\\nEnter your guess: ");
           guess = input.nextInt();
           if (guess == number)
               System.out.println("Yes, the number is " + number);
           else if (guess > number)
               System.out.println("Your guess is too high");
           else
               System.out.println("Your guess is too low");
       } // End of loop
   }
}

Example #2: An Advanced Math Tool

Write a program that generates five single-digit integer subtraction problems. Using a while loop, prompt the user to answer all five problems. After all of the answers are entered, report the number of the correct answers. Offer the user the opportunity to play the game again.

Solution: SubtractionQuizLoop

Make a new class named SubtractionQuizLoop. Inside, write the code shown below.

Example #3: Controlling a Loop with a Sentinel Value

Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. If data is not 0, it is added to the sum, and the next input data are read. If data is 0, the loop body is not executed, and the while loop terminates. If the first input read is 0, the loop body never executes, and the resulting sum is 0.

Suggested Output

Solution: SentinelValuedemo

Make a new class named SentinelValuedemo. Inside, write the code shown below.

Last updated