package Average; import java.util.Scanner;
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: public class Main { public static void main(String[] args) { } } 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. String name; int point1, point2, point3, point4; double average; Now we call in the scanner API and name it 'scanner' with lowercase letters. Scanner scanner = new Scanner(System.in); After declaring our scanner, we can let the user know what they need to input by printing instructions into the console. System.out.print("Enter your name:"); name = scanner.nextLine(); System.out.println("Enter 4 numbers:"); 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: point1 = scanner.nextInt(); point2 = scanner.nextInt(); point3 = scanner.nextInt(); point4 = scanner.nextInt(); scanner.close(); 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:
average = (double) (point1 + point2 + point3 + point4) / 4;
System.out.println("Hey " + name + ", your average score is: " + average);