Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class average {
- public static void main(String[] arguments) {
- //Counts the number of Legal Values entered
- int count=0;
- double i;
- double sum;
- //Initializing scanner to take input
- Scanner user_input = new Scanner(System.in);
- //Printing statement to user regarding how to use program
- System.out.println("Please Enter the integers. Enter -1 to terminate\n");
- System.out.println("Please note that non-numeric characters and negative integers(other than -1) will be ignored\n");
- System.out.println("Floats will be cast as decimals\n");
- //This variable stores sum of the numbers entered
- sum = 0.0;
- do{
- i=user_input.nextDouble();
- //breaking loop where user enters -1 the very first time
- if ((int)i == -1){
- break;
- }
- //ignoring negative values less than -1
- if ((int)i < -1){
- //System.out.println("went wrong 1\n");
- continue;
- }
- //Increasing Count and calculating sum if legal value entered
- count = count+1;
- sum=sum+i;
- }while ((int)i != -1 && !i.hasNextDouble()) ;
- //Count will be zero only when user enters -1 the very first time.
- if(count > 0){
- System.out.println("The Average is: " + (double)sum/(double)count);
- }
- else {
- System.out.println("See you next time then\n");
- }
- user_input.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement