Advertisement
Zidinjo

Exercise9

Feb 28th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. package Exercise9;
  2.  
  3. import java.util.Scanner;
  4.  
  5. /**
  6.  * @author Marvin Exercise9 - Sum and Average
  7.  *
  8.  *         Read, from standard input a series of integers, one per line, ending
  9.  *         in a sentinel value of 999. The numbers will be in the range 0 to
  10.  *         100. Output on a line Sum: followed by the sum of the series of
  11.  *         integers as shown below. Output on a new line Average: followed by
  12.  *         the mean average of the series of numbers formatted to a precision of
  13.  *         2 decimal places as shown below
  14.  */
  15.  
  16. public class Exercise9 {
  17.  
  18.     private final static int SENTINEL_VALUE = 999;
  19.  
  20.     public static void main(String[] args) {
  21.         Scanner scanner = new Scanner(System.in);
  22.  
  23.         boolean finished = false;
  24.         int counter = 0;
  25.         int values = 0;
  26.  
  27.         System.out.println("Please insert random numbers");
  28.  
  29.         while (!finished) {
  30.             if (scanner.hasNextInt()) {
  31.                 int enteredValue = scanner.nextInt();
  32.  
  33.                 if (enteredValue == Exercise9.SENTINEL_VALUE) {
  34.                     finished = true;
  35.                 } else {
  36.                     values += enteredValue;
  37.                     counter++;
  38.                 }
  39.             } else {
  40.                 scanner.next();
  41.                 System.out.println("In this program are only numbers allowed");
  42.             }
  43.         }
  44.  
  45.         if (counter != 0)
  46.             System.out.printf("Sum: %d \nAverage: %.2f", values, (values / (double) counter));
  47.  
  48.         scanner.close();
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement