Java Beginner’s Exercise #3 – Calculating the Average (With Solution)

This is the third exercise in the series of Java Beginner’s Exercises

In this exercise, we will be writing a Java program that will ask the user to input certain numbers.

Then the program will calculate the average of those numbers and displays it to the user.

Problem

Write a simple program that will ask the user to enter three numbers as inputs.

Then, calculate the average of those three numbers and return it through the program. 

I will be using the number 14, 15, 21 as inputs for this exercise.

However, the program must be written in a way that it can calculate the average of any numbers that are given as inputs. 

Note

First, let’s recall how to calculate the average of any given numbers.

To calculate the average, simply add up all the given numbers and divide them by how many numbers you just added.

In other words, the total sum of numbers divided by the number of numbers should give us the average.

Sample Solution

import java.util.*;

     public class theAverage {

     public static void main(String[] args) {
       Scanner in = new Scanner(System.in);

      System.out.print("Input your first number here: ");
      int firstNum = in.nextInt();

      System.out.print("Input your second number here: ");
      int secondNum = in.nextInt();

      System.out.print("Input your third number here: ");
      int thirdNum = in.nextInt();

System.out.println("The average is: " + (firstNum + secondNum + thirdNum) / 3);
         }

}

Expected Output

Your answer should be 16, if your input is 14,15 and 21.

Conclusion

This concludes the third exercise of the Java Beginner’s Exercise series. Although this is not an advanced exercise.

But, this can definitely help you if you have just started to program in Java.

Finding out the average in Java should be fairly simple to understand.

You can always modify the inputs and use different numbers for this exercise. Also, don’t forget to explore different options and play around with the code. 

I highly recommend you to check out the other Java exercises on my blog. And don’t forget to comment below if you have any questions or concerns.

Leave a Reply