如何创建 Java 固定大小数组

JavaBeginner
立即练习

介绍

本教程探讨了在 Java 中创建和使用固定大小数组的基本技术。数组是基本的数据结构,允许你将多个相同类型的元素存储在单个变量中。通过掌握 Java 数组,你将获得一项关键的编程技能,为更高级的主题奠定基础。

在这个实验(Lab)中,你将通过实践学习如何声明、初始化和操作数组。每个步骤都建立在之前的步骤之上,为你提供对 Java 中数组操作的全面理解。

创建你的第一个 Java 数组

Java 中的数组是存储相同类型多个变量的对象。与某些其他数据结构不同,一旦创建了数组,其大小就无法更改。这使得数组对于存储预定数量的元素特别有效。

数组声明和初始化

数组可以用不同的方式创建。让我们探索最常用的方法。

创建一个简单的整数数组

首先,让我们在我们的项目目录中创建一个新的 Java 文件。在 WebIDE 中,单击“File”菜单,选择“New File”,并将其命名为 ArrayDemo.java

将以下代码添加到你的文件中:

public class ArrayDemo {
    public static void main(String[] args) {
        // Method 1: Declare and initialize an array separately
        int[] numbers;       // Array declaration
        numbers = new int[5]; // Array initialization with size 5

        // Default values are assigned (all zeros for int array)
        System.out.println("Array elements after initialization:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        System.out.println("\nArray length: " + numbers.length);
    }
}

要编译并运行你的 Java 程序,请在 WebIDE 中打开一个终端(如果尚未打开),并执行以下命令:

javac ArrayDemo.java
java ArrayDemo

你应该看到类似于以下的输出:

Array elements after initialization:
numbers[0] = 0
numbers[1] = 0
numbers[2] = 0
numbers[3] = 0
numbers[4] = 0

Array length: 5

正如你所看到的,Java 会自动将整数数组中的所有元素初始化为零。

使用值初始化数组

现在,让我们修改我们的 ArrayDemo.java 文件,以包含另一种创建数组的方法——使用特定值进行初始化:

public class ArrayDemo {
    public static void main(String[] args) {
        // Method 1: Declare and initialize an array separately
        int[] numbers;       // Array declaration
        numbers = new int[5]; // Array initialization with size 5

        // Default values are assigned (all zeros for int array)
        System.out.println("Array elements after initialization:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        System.out.println("\nArray length: " + numbers.length);

        // Method 2: Initialize with specific values
        int[] scores = {85, 90, 75, 88, 92};

        System.out.println("\nScores array elements:");
        for (int i = 0; i < scores.length; i++) {
            System.out.println("scores[" + i + "] = " + scores[i]);
        }
    }
}

编译并运行更新后的程序:

javac ArrayDemo.java
java ArrayDemo

你现在应该看到额外的输出:

Array elements after initialization:
numbers[0] = 0
numbers[1] = 0
numbers[2] = 0
numbers[3] = 0
numbers[4] = 0

Array length: 5

Scores array elements:
scores[0] = 85
scores[1] = 90
scores[2] = 75
scores[3] = 88
scores[4] = 92

创建不同类型的数组

让我们创建一个名为 ArrayTypes.java 的新文件,以演示不同数据类型的数组。在 WebIDE 中,创建一个新文件并添加以下代码:

public class ArrayTypes {
    public static void main(String[] args) {
        // String array
        String[] names = new String[3];
        names[0] = "Alice";
        names[1] = "Bob";
        names[2] = "Charlie";

        System.out.println("String array elements:");
        for (int i = 0; i < names.length; i++) {
            System.out.println("names[" + i + "] = " + names[i]);
        }

        // Double array with initialization
        double[] prices = {19.99, 29.99, 15.50, 99.99};

        System.out.println("\nDouble array elements:");
        for (int i = 0; i < prices.length; i++) {
            System.out.println("prices[" + i + "] = " + prices[i]);
        }

        // Boolean array
        boolean[] flags = new boolean[3];
        flags[0] = true;

        System.out.println("\nBoolean array elements:");
        for (int i = 0; i < flags.length; i++) {
            System.out.println("flags[" + i + "] = " + flags[i]);
        }
    }
}

编译并运行此程序:

javac ArrayTypes.java
java ArrayTypes

你将看到以下输出:

String array elements:
names[0] = Alice
names[1] = Bob
names[2] = Charlie

Double array elements:
prices[0] = 19.99
prices[1] = 29.99
prices[2] = 15.5
prices[3] = 99.99

Boolean array elements:
flags[0] = true
flags[1] = false
flags[2] = false

请注意,不同的数据类型具有不同的默认值:

  • 数值类型(int、double 等)默认为零
  • 布尔值默认为 false
  • 引用类型(String、对象)默认为 null

此步骤向你展示了在 Java 中创建数组的基础知识。你已经学习了如何声明数组,如何使用和不使用值来初始化它们,以及如何创建不同数据类型的数组。

使用数组元素

现在我们知道了如何创建数组,让我们来探索如何使用数组元素。这包括设置值、访问元素和修改数组内容。

访问和修改数组元素

在你的 WebIDE 中创建一个名为 ArrayOperations.java 的新文件,其中包含以下代码:

public class ArrayOperations {
    public static void main(String[] args) {
        // Create an integer array
        int[] numbers = new int[5];

        // Assign values to array elements
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        // Display the original array
        System.out.println("Original array elements:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        // Access specific elements
        int firstElement = numbers[0];
        int thirdElement = numbers[2];

        System.out.println("\nAccessing specific elements:");
        System.out.println("First element: " + firstElement);
        System.out.println("Third element: " + thirdElement);

        // Modify array elements
        numbers[1] = 25;    // Change second element
        numbers[4] = 55;    // Change last element

        // Display the modified array
        System.out.println("\nArray after modification:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }
    }
}

编译并运行此程序:

javac ArrayOperations.java
java ArrayOperations

你应该看到以下输出:

Original array elements:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Accessing specific elements:
First element: 10
Third element: 30

Array after modification:
numbers[0] = 10
numbers[1] = 25
numbers[2] = 30
numbers[3] = 40
numbers[4] = 55

数组边界和异常处理

在使用数组时,了解数组边界至关重要。Java 数组具有固定大小,尝试访问超出这些边界的元素将导致异常。

创建一个名为 ArrayBoundaries.java 的新文件,其中包含以下代码:

public class ArrayBoundaries {
    public static void main(String[] args) {
        int[] numbers = new int[3];  // Array with 3 elements (indices 0, 1, 2)

        // Set values within boundaries
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;

        System.out.println("Array elements within boundaries:");
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        // Demonstrating boundary checking with try-catch
        System.out.println("\nAttempting to access elements outside boundaries:");

        try {
            // This is valid
            System.out.println("Accessing numbers[2]: " + numbers[2]);

            // This will cause an ArrayIndexOutOfBoundsException
            System.out.println("Attempting to access numbers[3]: " + numbers[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
            System.out.println("Cannot access an index outside the array bounds (0 to " + (numbers.length-1) + ")");
        }
    }
}

编译并运行此程序:

javac ArrayBoundaries.java
java ArrayBoundaries

你应该看到类似这样的输出:

Array elements within boundaries:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30

Attempting to access elements outside boundaries:
Accessing numbers[2]: 30
Error: Index 3 out of bounds for length 3
Cannot access an index outside the array bounds (0 to 2)

这表明 Java 对数组执行边界检查。尝试访问 numbers[3] 会抛出异常,因为数组只有索引为 0、1 和 2 的元素。

在数组中计算和存储值

让我们创建一个实际的例子,在其中计算值并将它们存储在数组中。创建一个名为 TemperatureConverter.java 的文件:

public class TemperatureConverter {
    public static void main(String[] args) {
        // Array to store Celsius temperatures
        double[] celsiusTemps = {0, 10, 20, 30, 40};

        // Array to store converted Fahrenheit temperatures
        double[] fahrenheitTemps = new double[celsiusTemps.length];

        // Convert each Celsius temperature to Fahrenheit
        for (int i = 0; i < celsiusTemps.length; i++) {
            // Formula: F = C * 9/5 + 32
            fahrenheitTemps[i] = celsiusTemps[i] * 9/5 + 32;
        }

        // Display the conversion table
        System.out.println("Temperature Conversion Table:");
        System.out.println("---------------------------");
        System.out.println("Celsius    |    Fahrenheit");
        System.out.println("---------------------------");

        for (int i = 0; i < celsiusTemps.length; i++) {
            System.out.printf("%-10.1f |    %-10.1f\n",
                             celsiusTemps[i],
                             fahrenheitTemps[i]);
        }
    }
}

编译并运行此程序:

javac TemperatureConverter.java
java TemperatureConverter

输出将是一个温度转换表:

Temperature Conversion Table:
---------------------------
Celsius    |    Fahrenheit
---------------------------
0.0        |    32.0
10.0       |    50.0
20.0       |    68.0
30.0       |    86.0
40.0       |    104.0

此示例演示了如何使用数组来存储相关数据并有效地对多个值执行计算。

在这一步中,你已经学习了如何访问和修改数组元素,处理数组边界,以及将数组用于实际计算。这些技能构成了更复杂数组操作的基础。

高级数组操作

现在你了解了数组的基础知识,让我们来探索更复杂的操作,包括数组迭代、搜索以及将数组与方法一起使用。

数组迭代技术

Java 提供了多种遍历数组元素的方法。创建一个名为 ArrayIteration.java 的新文件,其中包含以下代码:

public class ArrayIteration {
    public static void main(String[] args) {
        // Create a sample array
        String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

        System.out.println("Array Iteration Methods:");

        // Method 1: Standard for loop
        System.out.println("\n1. Using standard for loop:");
        for (int i = 0; i < fruits.length; i++) {
            System.out.println("fruits[" + i + "] = " + fruits[i]);
        }

        // Method 2: Enhanced for loop (foreach)
        System.out.println("\n2. Using enhanced for loop (foreach):");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Method 3: While loop
        System.out.println("\n3. Using while loop:");
        int index = 0;
        while (index < fruits.length) {
            System.out.println("fruits[" + index + "] = " + fruits[index]);
            index++;
        }
    }
}

编译并运行此程序:

javac ArrayIteration.java
java ArrayIteration

你应该看到以下输出:

Array Iteration Methods:

1. Using standard for loop:
fruits[0] = Apple
fruits[1] = Banana
fruits[2] = Cherry
fruits[3] = Date
fruits[4] = Elderberry

2. Using enhanced for loop (foreach):
Apple
Banana
Cherry
Date
Elderberry

3. Using while loop:
fruits[0] = Apple
fruits[1] = Banana
fruits[2] = Cherry
fruits[3] = Date
fruits[4] = Elderberry

每种迭代方法都有其优点:

  • 标准 for 循环:提供对数组索引和元素的访问
  • 增强 for 循环:当你只需要元素时,语法更简洁
  • While 循环:当迭代条件更复杂时很有用

在数组中搜索元素

让我们创建一个在数组中搜索元素的程序。创建一个名为 ArraySearch.java 的文件:

public class ArraySearch {
    public static void main(String[] args) {
        // Create an array of numbers
        int[] numbers = {10, 25, 33, 47, 52, 68, 79};

        // Values to search for
        int[] searchValues = {33, 50, 79};

        for (int valueToFind : searchValues) {
            boolean found = false;
            int position = -1;

            // Search through the array
            for (int i = 0; i < numbers.length; i++) {
                if (numbers[i] == valueToFind) {
                    found = true;
                    position = i;
                    break;  // Exit the loop once found
                }
            }

            // Display result
            if (found) {
                System.out.println(valueToFind + " found at position " + position);
            } else {
                System.out.println(valueToFind + " not found in the array");
            }
        }
    }
}

编译并运行此程序:

javac ArraySearch.java
java ArraySearch

你应该看到类似这样的输出:

33 found at position 2
50 not found in the array
79 found at position 6

这演示了一种基本的线性搜索算法,检查每个元素,直到找到目标值或数组被遍历完。

将数组传递给方法

数组可以像任何其他变量一样传递给方法。创建一个名为 ArrayMethods.java 的文件:

public class ArrayMethods {
    public static void main(String[] args) {
        // Create an array
        int[] values = {5, 10, 15, 20, 25};

        // Display the original array
        System.out.println("Original array:");
        displayArray(values);

        // Calculate and display the sum
        int sum = calculateSum(values);
        System.out.println("\nSum of all elements: " + sum);

        // Calculate and display the average
        double average = calculateAverage(values);
        System.out.println("Average of all elements: " + average);

        // Double all values in the array
        doubleValues(values);

        // Display the modified array
        System.out.println("\nArray after doubling all values:");
        displayArray(values);
    }

    // Method to display an array
    public static void displayArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    // Method to calculate the sum of array elements
    public static int calculateSum(int[] arr) {
        int sum = 0;
        for (int value : arr) {
            sum += value;
        }
        return sum;
    }

    // Method to calculate the average of array elements
    public static double calculateAverage(int[] arr) {
        int sum = calculateSum(arr);
        return (double) sum / arr.length;
    }

    // Method to double all values in the array
    public static void doubleValues(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 2;
        }
    }
}

编译并运行此程序:

javac ArrayMethods.java
java ArrayMethods

你应该看到类似这样的输出:

Original array:
5 10 15 20 25

Sum of all elements: 75
Average of all elements: 15.0

Array after doubling all values:
10 20 30 40 50

此示例演示了几个重要的概念:

  1. 数组可以作为参数传递给方法
  2. 方法可以返回从数组计算的值
  3. 在方法内部对数组元素所做的更改会反映在方法外部(数组通过引用传递)

查找最大值和最小值

让我们创建一个程序来查找数组中的最大值和最小值。创建一个名为 ArrayMinMax.java 的文件:

public class ArrayMinMax {
    public static void main(String[] args) {
        // Create an array of numbers
        int[] numbers = {42, 17, 88, 23, 56, 9, 71, 33};

        // Find minimum and maximum values
        int min = findMinimum(numbers);
        int max = findMaximum(numbers);

        // Display the array
        System.out.print("Array values: ");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();

        // Display results
        System.out.println("Minimum value: " + min);
        System.out.println("Maximum value: " + max);
    }

    // Method to find the minimum value in an array
    public static int findMinimum(int[] arr) {
        // Start with the first element as the minimum
        int min = arr[0];

        // Compare with other elements
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] < min) {
                min = arr[i];
            }
        }

        return min;
    }

    // Method to find the maximum value in an array
    public static int findMaximum(int[] arr) {
        // Start with the first element as the maximum
        int max = arr[0];

        // Compare with other elements
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }

        return max;
    }
}

编译并运行此程序:

javac ArrayMinMax.java
java ArrayMinMax

你应该看到类似这样的输出:

Array values: 42 17 88 23 56 9 71 33
Minimum value: 9
Maximum value: 88

在这一步中,你已经学习了几种高级数组操作,包括不同的迭代技术、搜索元素、将数组传递给方法以及查找最大值和最小值。这些技能将帮助你更有效地在 Java 程序中使用数组。

实际的数组应用

在最后一步,我们将通过一个完整的例子来探索数组的实际应用。我们将创建一个简单的成绩管理系统,该系统演示了如何在现实世界的编程场景中使用数组。

创建一个学生成绩跟踪器

让我们构建一个管理学生成绩的程序。该程序将:

  1. 存储学生姓名及其成绩
  2. 计算平均成绩
  3. 查找最高和最低成绩
  4. 确定有多少学生的得分高于平均水平

在你的 WebIDE 中创建一个名为 GradeTracker.java 的新文件:

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);
    }
}

编译并运行此程序:

javac GradeTracker.java
java GradeTracker

你应该看到类似这样的输出:

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

该程序演示了如何使用数组来管理相关数据(学生姓名和成绩)并对该数据执行计算。

添加成绩类别

现在,让我们通过添加成绩类别来增强我们的成绩跟踪器。创建一个名为 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 + ")";
    }
}

编译并运行此程序:

javac EnhancedGradeTracker.java
java EnhancedGradeTracker

你应该看到类似这样的输出:

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)

这个增强的例子演示了:

  1. 使用多个数组来存储相关数据
  2. 创建用于计算和格式化的实用方法
  3. 计数和分类数据
  4. 创建数组数据的可视化表示

基于条件处理数组数据

对于我们的最后一个例子,让我们创建一个程序,该程序基于条件处理数组数据。创建一个名为 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);
    }
}

编译并运行此程序:

javac FilteredGrades.java
java FilteredGrades

你应该看到类似这样的输出:

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%

此示例演示了:

  1. 将条件逻辑与数组一起使用
  2. 根据条件创建过滤后的数组
  3. 从数组数据计算统计数据
  4. 以格式化的方式呈现信息

在这一步中,你已经看到了如何应用数组来解决实际问题。你已经学会了管理相关数据,执行计算,并根据条件创建数组数据的过滤视图。这些技能将为你使用数组在现实世界的 Java 应用程序中打下坚实的基础。

总结

在这个实验中,你探索了在 Java 中创建和使用固定大小数组的基本技术。你学会了如何:

  • 声明和初始化不同数据类型的数组
  • 访问和修改数组元素,同时遵守数组边界
  • 使用不同的循环技术遍历数组
  • 将数组传递给方法并处理数组数据
  • 查找数组中的最小值和最大值
  • 将数组应用于实际问题,例如成绩跟踪

数组构成了 Java 中许多数据结构的基础,并且对于高效的数据存储和操作至关重要。你在本实验中开发的技能将作为更高级编程概念(如动态数据结构、算法和面向对象编程)的构建模块。

继续通过修改提供的示例、创建你自己的基于数组的应用程序,以及探索 Java 文档中 java.util.Arrays 类中的其他数组实用程序来练习数组。