How to Write a Java Program that Takes Average

In this post, I will be explaining how to write a Java program that takes the average of user inputs in the format of 4 different variables. These variables are numbers, and the average will be a double type. The program will print the results on the command line.

We can start off by creating a class in your favorite IDE. It doesn't matter if it's Eclipse, IntelliJ, VSCode, or any other IDE.

You can first create a package and then a class inside the package, but it is up to you which one you will go with.

I will leave the GitHub link at the bottom for those who want to see it there.

First, I created a package named "Average" and then imported the Java scanner API to create a scanner object later on in my code:

Now we have mentioned our package and imported the scanner API. We saved this inside our Main.java file, which is the "Main" class's file name.

In order for our code to work when we execute, we need to declare our class in a proper way. That is why we add the below code:

Now we have a class and a static void main method. The next step is to fill the 'main' method with the actual algorithm for taking the average.

Now we call in the scanner API and name it 'scanner' with lowercase letters.

After declaring our scanner, we can let the user know what they need to input by printing instructions into the console.

As you have noticed in the second line of the above code, I called the String 'name' we created earlier and gave "scanner.nextLine()" as a value. This is an instruction that tells Java to read the input (including spaces) until the user skips the line by pressing 'enter'.

And at last, we printed another sentence telling the user to enter four numbers.

Now we want the user to enter four different inputs, and we want to make sure they are entered line by line. That's why we write it in this form:

As you can see, we ended it with "scanner.close()". This informs the scanner API that we are done taking inputs.

Now we are at the last step. We calculate the contents of the 'average' variable (double) and print out the results for the user:

You can post your questions below in the comments.

GitHub Link

June 9, 2023