➤ Hello World program
➤ Java Addition Program
➤ Average of 2 Numbers
➤ Average of 3 Numbers
➤ Simple Interest in Java
➤ Compound Interest
➤ Display ASCII Value
➤ Area of Circle Java
➤ Area of Rectangle
➤ Java Area of Triangle
➤ Java Swap 2 Numbers
➤ Distance b/w 2 Points
Java Flow Control Program
Java Array Programs
Java String Programs
Java Program to Calculate Total & Average of Three Subjects | Program description:- Write a program in Java to calculate the average of three subjects and display total and average marks.
In this program, we will take input from the end-user and for this, we will use the Scanner class object. The marks in subjects will be an integer value therefore we will declare three integer type variables to store the input value. The sum of marks also will be an integer value but the average can be an integer or floating-point value, therefore, we will take the sum variable as an integer type and the average variable as a double type.
If the three subjects marks are represented as mark1, mark2, and mark3. Then,
Total Mark = mark1 + mark2 + mark3
Average Mark = (Total mark) / 3
Based on these formulas we can calculate the total marks and average marks for the given three subjects. Let us develop the program and demonstrate it through some examples:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// variables to store marks
int mark1, mark2, mark3;
// variables to store sum and average marks
int totalMark;
double avgMark;
// create Scanner class object to take input
Scanner scan = new Scanner(System.in);
System.out.println("Enter marks of three subjects: ");
mark1 = scan.nextInt();
mark2 = scan.nextInt();
mark3 = scan.nextInt();
// calculate sum of marks
totalMark = mark1 + mark2 + mark3;
// calculate average of marks
avgMark = (double) totalMark / 3;
System.out.println("Total Mark: " + totalMark);
System.out.println("Average Mark: " + Math.round(avgMark));
scan.close();
}
}
Output for different test-cases:-
Enter marks of three subjects:
70 75 86
Total Mark: 231
Average Mark: 77
Enter marks of three subjects:
65 81 59
Total Mark: 205
Average Mark: 68
Enter marks of three subjects:
45 52 61
Total Mark: 158
Average Mark: 53
While calculating the average mark value the total mark is in the integer so when we divide it with some value the result will be an integer, therefore we have to typecast the integer value of the total mark to double value and after that, we have calculated the average value.
While displaying the result we have used Math.round() method for the average mark. The java.lang.Math.round() method returns the closest value to the argument, with ties rounding to positive infinity.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!