Advertisement
Guest User

Untitled

a guest
Sep 16th, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. import java.util.Scanner;
  2. public class average {
  3.   public static void main(String[] arguments) {
  4.     //Counts the number of Legal Values entered
  5.     int count=0;
  6.     double i;
  7.     double sum;
  8.     //Initializing scanner to take input
  9.     Scanner user_input = new Scanner(System.in);
  10.     //Printing statement to user regarding how to use program
  11.     System.out.println("Please Enter the integers. Enter -1 to terminate\n");
  12.     System.out.println("Please note that non-numeric characters and negative integers(other than -1) will be ignored\n");
  13.     System.out.println("Floats will be cast as decimals\n");
  14.     //This variable stores sum of the numbers entered
  15.     sum = 0.0;
  16.     do{
  17.         i=user_input.nextDouble();
  18.         //breaking loop where user enters -1 the very first time
  19.         if ((int)i == -1){
  20.                 break;
  21.                 }
  22.         //ignoring negative values less than -1
  23.         if ((int)i < -1){
  24.                 //System.out.println("went wrong 1\n");
  25.                 continue;
  26.                 }
  27.                
  28.         //Increasing Count and calculating sum if legal value entered
  29.         count = count+1;
  30.         sum=sum+i;
  31.        
  32.         }while ((int)i != -1 && !i.hasNextDouble()) ;
  33.     //Count will be zero only when user enters -1 the very first time.
  34.     if(count > 0){
  35.                     System.out.println("The Average is: " + (double)sum/(double)count);
  36.                     }
  37.     else {
  38.             System.out.println("See you next time then\n");
  39.             }
  40.    
  41.     user_input.close();
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement