In Java Write a sentinel controlled while loop that keeps re

In Java

Write a sentinel controlled while loop that keeps reading in an integer until the user types in -999. The loop should add the integers and keep track of how many integers were read.

Solution

Hi,

Please see below Java class and sample output. Please comment for any queries.feedbacks.

thanks,

Anita

LoopTester.java

import java.util.Scanner;


public class LoopTester {

   public static void main(String [] args){
       String numberStr = \"\";
       int number =0;
       int sum =0;
       int count = 0;

       //Asking the number to enter numbers
       Scanner scan = new Scanner(System.in);
       System.out.println(\"Please enter numbers, and enter -999 to exit: \");

       numberStr = scan.nextLine();
       number = Integer.valueOf(numberStr);
       sum = sum + number; // Adding the sum for the first number
       count = count+1;     // Incrementing the counter for the first number

       while(-999 != number ){
           numberStr = scan.nextLine();
           number = Integer.valueOf(numberStr);
           if(-999 != number){
               sum = sum + number; // Adding the sum in loop
               count = count +1; // Incrementing the counter in loop
           }
       }

       //Displaying the count adn sum
       System.out.println(\" Count :\"+count);
       System.out.println(\" Sum :\"+sum);
   }
}

Sample output:

Please enter numbers, and enter -999 to exit:
3
4
5
6
7
-999
Count :5
Sum :25

In Java Write a sentinel controlled while loop that keeps reading in an integer until the user types in -999. The loop should add the integers and keep track of
In Java Write a sentinel controlled while loop that keeps reading in an integer until the user types in -999. The loop should add the integers and keep track of

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site