Practical Array Applications
In this final step, we'll explore practical applications of arrays through a complete example. We'll create a simple grade management system that demonstrates how arrays can be used in real-world programming scenarios.
Creating a Student Grade Tracker
Let's build a program that manages student grades. This program will:
- Store student names and their grades
- Calculate the average grade
- Find the highest and lowest grades
- Determine how many students scored above average
Create a new file named GradeTracker.java
in your WebIDE:
public class GradeTracker {
public static void main(String[] args) {
// Arrays to store student information
String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
"Frank", "Grace", "Hannah", "Ian", "Julia"};
int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};
// Display all student records
System.out.println("Student Grade Records:");
System.out.println("---------------------");
System.out.println("Name\t\tGrade");
System.out.println("---------------------");
for (int i = 0; i < studentNames.length; i++) {
// Add extra tab for short names to align columns
String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(studentNames[i] + tab + studentGrades[i]);
}
// Calculate statistics
int sum = 0;
int highest = studentGrades[0];
int lowest = studentGrades[0];
String highestStudent = studentNames[0];
String lowestStudent = studentNames[0];
for (int i = 0; i < studentGrades.length; i++) {
// Add to sum for average calculation
sum += studentGrades[i];
// Check for highest grade
if (studentGrades[i] > highest) {
highest = studentGrades[i];
highestStudent = studentNames[i];
}
// Check for lowest grade
if (studentGrades[i] < lowest) {
lowest = studentGrades[i];
lowestStudent = studentNames[i];
}
}
// Calculate average
double average = (double) sum / studentGrades.length;
// Count students above average
int aboveAverageCount = 0;
for (int grade : studentGrades) {
if (grade > average) {
aboveAverageCount++;
}
}
// Display statistics
System.out.println("\nClass Statistics:");
System.out.println("----------------");
System.out.printf("Class Average: %.2f\n", average);
System.out.println("Highest Grade: " + highest + " (" + highestStudent + ")");
System.out.println("Lowest Grade: " + lowest + " (" + lowestStudent + ")");
System.out.println("Number of students above average: " + aboveAverageCount);
}
}
Compile and run this program:
javac GradeTracker.java
java GradeTracker
You should see output like this:
Student Grade Records:
---------------------
Name Grade
---------------------
Alice 85
Bob 92
Charlie 78
David 65
Emma 88
Frank 72
Grace 95
Hannah 83
Ian 79
Julia 91
Class Statistics:
----------------
Class Average: 82.80
Highest Grade: 95 (Grace)
Lowest Grade: 65 (David)
Number of students above average: 5
This program demonstrates how arrays can be used to manage related data (student names and grades) and perform calculations on that data.
Adding Grade Categories
Now, let's enhance our grade tracker by adding grade categories. Create a new file named EnhancedGradeTracker.java
:
public class EnhancedGradeTracker {
public static void main(String[] args) {
// Arrays to store student information
String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
"Frank", "Grace", "Hannah", "Ian", "Julia"};
int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};
// Create arrays to count grades in each category
int[] gradeCounts = new int[5]; // A, B, C, D, F
// Display all student records with grade categories
System.out.println("Student Grade Records:");
System.out.println("------------------------------");
System.out.println("Name\t\tScore\tGrade");
System.out.println("------------------------------");
for (int i = 0; i < studentNames.length; i++) {
// Calculate letter grade
char letterGrade = calculateGrade(studentGrades[i]);
// Count grades by category
switch (letterGrade) {
case 'A': gradeCounts[0]++; break;
case 'B': gradeCounts[1]++; break;
case 'C': gradeCounts[2]++; break;
case 'D': gradeCounts[3]++; break;
case 'F': gradeCounts[4]++; break;
}
// Add extra tab for short names to align columns
String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(studentNames[i] + tab + studentGrades[i] + "\t" + letterGrade);
}
// Calculate statistics
double average = calculateAverage(studentGrades);
// Display statistics
System.out.println("\nClass Statistics:");
System.out.println("----------------");
System.out.printf("Class Average: %.2f\n", average);
// Display grade distribution
System.out.println("\nGrade Distribution:");
System.out.println("------------------");
System.out.println("A: " + displayStars(gradeCounts[0]));
System.out.println("B: " + displayStars(gradeCounts[1]));
System.out.println("C: " + displayStars(gradeCounts[2]));
System.out.println("D: " + displayStars(gradeCounts[3]));
System.out.println("F: " + displayStars(gradeCounts[4]));
}
// Method to calculate the letter grade from a numeric score
public static char calculateGrade(int score) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else if (score >= 70) {
return 'C';
} else if (score >= 60) {
return 'D';
} else {
return 'F';
}
}
// Method to calculate the average of an integer array
public static double calculateAverage(int[] arr) {
int sum = 0;
for (int value : arr) {
sum += value;
}
return (double) sum / arr.length;
}
// Method to create a string of stars representing a count
public static String displayStars(int count) {
StringBuilder stars = new StringBuilder();
for (int i = 0; i < count; i++) {
stars.append("*");
}
return stars.toString() + " (" + count + ")";
}
}
Compile and run this program:
javac EnhancedGradeTracker.java
java EnhancedGradeTracker
You should see output like this:
Student Grade Records:
------------------------------
Name Score Grade
------------------------------
Alice 85 B
Bob 92 A
Charlie 78 C
David 65 D
Emma 88 B
Frank 72 C
Grace 95 A
Hannah 83 B
Ian 79 C
Julia 91 A
Class Statistics:
----------------
Class Average: 82.80
Grade Distribution:
------------------
A: *** (3)
B: *** (3)
C: *** (3)
D: * (1)
F: (0)
This enhanced example demonstrates:
- Using multiple arrays to store related data
- Creating utility methods for calculations and formatting
- Counting and categorizing data
- Creating a visual representation of array data
Processing Array Data Based on Conditions
For our final example, let's create a program that processes array data based on conditions. Create a file named FilteredGrades.java
:
public class FilteredGrades {
public static void main(String[] args) {
// Arrays to store student information
String[] studentNames = {"Alice", "Bob", "Charlie", "David", "Emma",
"Frank", "Grace", "Hannah", "Ian", "Julia"};
int[] studentGrades = {85, 92, 78, 65, 88, 72, 95, 83, 79, 91};
// Create a threshold for passing
int passingGrade = 75;
// Display all student records with pass/fail status
System.out.println("Student Grade Records:");
System.out.println("------------------------------");
System.out.println("Name\t\tScore\tStatus");
System.out.println("------------------------------");
// Count passing and failing students
int passingCount = 0;
for (int i = 0; i < studentNames.length; i++) {
String status = (studentGrades[i] >= passingGrade) ? "PASS" : "FAIL";
// Count passing students
if (studentGrades[i] >= passingGrade) {
passingCount++;
}
// Add extra tab for short names to align columns
String tab = studentNames[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(studentNames[i] + tab + studentGrades[i] + "\t" + status);
}
// Create arrays to store only passing students
String[] passingStudents = new String[passingCount];
int[] passingScores = new int[passingCount];
// Fill the passing student arrays
int index = 0;
for (int i = 0; i < studentNames.length; i++) {
if (studentGrades[i] >= passingGrade) {
passingStudents[index] = studentNames[i];
passingScores[index] = studentGrades[i];
index++;
}
}
// Display only passing students
System.out.println("\nPassing Students (Score >= 75):");
System.out.println("------------------------------");
System.out.println("Name\t\tScore");
System.out.println("------------------------------");
for (int i = 0; i < passingStudents.length; i++) {
// Add extra tab for short names to align columns
String tab = passingStudents[i].length() <= 5 ? "\t\t" : "\t";
System.out.println(passingStudents[i] + tab + passingScores[i]);
}
// Calculate and display statistics
System.out.println("\nClass Statistics:");
System.out.println("----------------");
System.out.println("Total Students: " + studentNames.length);
System.out.println("Passing: " + passingCount);
System.out.println("Failing: " + (studentNames.length - passingCount));
System.out.printf("Pass Rate: %.1f%%\n",
(double) passingCount / studentNames.length * 100);
}
}
Compile and run this program:
javac FilteredGrades.java
java FilteredGrades
You should see output like this:
Student Grade Records:
------------------------------
Name Score Status
------------------------------
Alice 85 PASS
Bob 92 PASS
Charlie 78 PASS
David 65 FAIL
Emma 88 PASS
Frank 72 FAIL
Grace 95 PASS
Hannah 83 PASS
Ian 79 PASS
Julia 91 PASS
Passing Students (Score >= 75):
------------------------------
Name Score
------------------------------
Alice 85
Bob 92
Charlie 78
Emma 88
Grace 95
Hannah 83
Ian 79
Julia 91
Class Statistics:
----------------
Total Students: 10
Passing: 8
Failing: 2
Pass Rate: 80.0%
This example demonstrates:
- Using conditional logic with arrays
- Creating filtered arrays based on conditions
- Calculating statistics from array data
- Presenting information in a formatted way
In this step, you've seen how arrays can be applied to solve practical problems. You've learned to manage related data, perform calculations, and create filtered views of array data based on conditions. These skills will serve as a strong foundation for working with arrays in real-world Java applications.