Java Program for Calculating Average

In this article, we are going to create a command line application for calculating the Average. This application will be able to calculate the average with any number of numbers, there will be no limitations like it will take only 5 numbers or 6 numbers. You can consider this as a mini project for beginners in java

Average Java Code

Average.java

package gangforcode;

import java.util.InputMismatchException;

import java.util.Scanner;
public class Average{

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);

        System.out.println("Welcome to Percentage Calculate");

        boolean status = true;
        while(status)
        {
            System.out.println("Press 1 for calculating Average\nPress 2 for exit");
            int input = sc.nextInt();
            if(input ==2)
            {
                status  = false;
                System.out.println("Thanks for using !!!");
                break;
            }
            else
                averageCalculator();
        }


    }

    public static void averageCalculator(){
        Scanner sc = new Scanner(System.in);
        boolean status =true;
        float count =0;
        float sum =0;
        while(true)
        {
            System.out.println("Press X for stop");
            System.out.println("Enter the number");
            try {
                float temp = sc.nextFloat();
                if(temp==0)
                    return;
                else {
                    count++;
                    sum=sum+temp;
                    System.out.println("Average  = "+ sum/count);
                }
            }
            catch(InputMismatchException e)
            {
                return ;
            }
        }

    }

}

Average Java Output

average in java

In the above java code we can enter numbers and the average of all the given numbers is displayed simultaneously. The program will keep running until we did not stop it.

Thanks !!!

Leave a Comment