forked from SadeeshaJayaweera/Java-Practical-Codes-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion_5.java
More file actions
49 lines (38 loc) · 1.47 KB
/
Copy pathQuestion_5.java
File metadata and controls
49 lines (38 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Scanner;
import java.text.DecimalFormat;
/*
This is the Fifth question which is to Write a Java application that allows the user to enter
up to 20 integer grades into an array. Stop the loop by typing in ‐1.
Your main method should call an Average method that returns the average of the grades.
Use the DecimalFormat class to format the average to 2 decimal places
*/
public class Question_5 {
public static void main(String[] args)
{
int[] grades = new int[20];
int count = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter up to 20 integer grades (-1 to stop):");
int input = scanner.nextInt();
while (input != -1 && count < 20)
{
grades[count] = input;
count++;
input = scanner.nextInt();
}
double average = calculateAverage(grades, count);
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
String formattedAverage = decimalFormat.format(average);
System.out.println("Average grade: " + formattedAverage);
}
public static double calculateAverage(int[] grades, int count) {
if (count == 0) {
return 0.0;
}
int sum = 0;
for (int i = 0; i < count; i++) {
sum += grades[i];
}
return (double) sum / count;
}
}