In this tutorial, we will calculate average of numbers in different ways. We will calculate average of 2 integers with/without user input. And also we will create and use and average calculator mathod for calculating average. At last, we will use a while loop for calculating average for n numbers depending on user inputs
Calculate Average in Java
Solution 1: Calculatiing average of 2 integers
Note: Since int/int operations removes decimals, we have to use double values on upper part or bottom part of divison (or both).
Wrong example: 3/2 (Gives us 1)
Correct exampes: 3.0/2 or 3/2.0 or 3.0/2.0
int num1 = 6; int num2 = 7; double average=(double)(num1+num2)/2; //also could be (num1+num2)/2.0 or (double)(num1+num2)/2.0 System.out.println(average); //6.5
Solution 2: Calculatiing average of 2 integers (with user inputs)
import java.util.Scanner; public class averageWithUserInputs { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("What is the first number?"); int num1 = input.nextInt(); System.out.println("What is the first number?"); int num2 = input.nextInt(); double average=(double)(num1+num2)/2; //also could be (num1+num2)/2.0 or (double)(num1+num2)/2.0 System.out.println("Average of "+num1+" and "+num2+" is: "+average); //6.5 } }
Output:
What is the first number? 6 What is the first number? 7 Average of 6 and 7 is: 6.5
Solution 3: Calculating average of 2 integers with using average method
import java.util.Scanner; public class maxmin { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("What is the first number?"); int num1 = input.nextInt(); System.out.println("What is the first number?"); int num2 = input.nextInt(); double average=calculateAverage(num1,num2); //also could be (num1+num2)/2.0 or (double)(num1+num2)/2.0 System.out.println("Average of "+num1+" and "+num2+" is: "+average); //6.5 } public static double calculateAverage(int a, int b) { double avg = (double)(a+b)/2; return avg; } }
Solution 4: Calculating average of n integers with while loop
Scanner input = new Scanner(System.in); int sum=0; int count=0; System.out.println("Please input a positive number"); System.out.println("type a negative number to stop writing numbers and calculate average"); int number = input.nextInt(); while (number>=0) { sum+=number; count++; System.out.println("type a negative number to stop writing numbers and calculate average"); number = input.nextInt(); } double average=(double)sum/count; System.out.println("Average of your numbers is: "+average);