JAVA 学生成绩数组对

JAVA array pair for student grades

如何将学生数组与成绩数组配对?当我找到最高分时,相应的学生也应该显示,与最低分的学生一样。我不知道如何让这个程序在两个单独的数组中执行。

import java.util.Scanner;

public class Asm7 {

public static void main(String[] args) {
    
    Scanner Scan = new Scanner(System.in);
    
    System.out.println("How many students do you have?: ");
    int AMOUNT = 0;
    AMOUNT = Scan.nextInt();
    
    String[] STUDENT = new String [AMOUNT];

    int COUNTER = 0;
    
    int GRADE [] = new int [AMOUNT];
    
    if (AMOUNT <= 0) {
        
        System.out.println("Invalid student amount");
       
    } 
    
    else {
    
    for(int i = 0; i < AMOUNT; i++){
        
    System.out.println("Enter student's first name: " + (i+1));
    STUDENT[i] = Scan.next();
    System.out.println("Enter student's grade in order added: ");
    GRADE[i] = Scan.nextInt();  
    
    
    }
    
    
    
    for(int i = 0; i < AMOUNT; i++){
        
    System.out.println(STUDENT[i] + " received the final grade of " + GRADE[i]);}
    System.out.println();
    
    
    int [] Results = MinMax(GRADE);
    
    System.out.println("The highest grade in the class was " + Results[1]);
    System.out.println("The lowest grade in the class was "+ Results[0]);
    
    }}
    
    public static int[] MinMax(int[] value) {
        
        int[] Result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
        for (int i : value) {
            Result[0] = i < Result[0] ? i : Result[0];
            Result[1] = i > Result[1] ? i : Result[1];
        }
        return Result;

    }

}

如果数据未排序,最好在打印学生及其成绩后在同一个循环中同时查找 minmax 成绩。

然后不需要循环来打印 minmax 成绩:

for (int i = 0; i < amount; i++) {
    System.out.println(student[i] + " received the final grade of " + grade[i]);
}
int min = grade[0];
int max = grade[0];
for (int i = 1; i < amount; i++) {
    if (grade[i] < min) {
        min = grade[i];
    } else if (grade[i] > max) {
        max = grade[i];
    }
}

System.out.println("The highest grade in the class was " + max);
System.out.println("The lowest grade in the class was " + min);

如果要查找min/max的索引,就可以打印得到最低和最高成绩的学生的名字。

public static void main(String[] args) {

    int[] grades = new int[]{50, 51, 52, 50, 60, 22, 53, 70, 60, 94, 56, 41};

    int[] result = getMinMax(grades);

    System.out.println("Min: " + result[0] + ", Max: " + result[1]);
}

public static int[] getMinMax(int[] values) {

    int[] result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
    for (int i : values) {
        result[0] = i < result[0] ? i : result[0];
        result[1] = i > result[1] ? i : result[1];
    }
    return result;
}

您需要处理 int[] 值为 null 或空的情况。您可以决定(抛出异常,return null...或其他)

您对 学生人数 while 循环验证有点晚了。您希望在声明和初始化数组之前执行此操作。然而,while 循环实际上被用于尝试某种形式的验证这一事实是一个非常好的迹象。这比大多数新程序员倾向于做的要多。所有输入都应经过验证,并为用户提供提供正确解决方案的机会。这只会为用户带来更流畅、无故障的应用程序和更好的体验。看一下代码中的 while 循环:

while (amount < 0) {
    System.out.println("Invalid student amount");
}

如果用户提供 -1(这是一个有效的整数值,+1)会发生什么?没错……您的应用程序将进入无限循环,向控制台 Window 输出 Invalid student amount。您的验证方案应该包含整个提示,然后应该更合理地定义退出它的方法。对于 while 循环,最好通过其条件语句完成退出,如果条件为假则退出循环,例如:

Scanner scan = new Scanner(System.in);
    
// Number Of Students...
String inputString = "";
while (inputString.isEmpty()) {
    System.out.print("How many students do you have?: --> ");
    inputString = scan.nextLine().trim();
    /* Is the supplied Number Of Students valid and within 
       range (1 to 50 inclusive)?     */
    if (!inputString.matches("\d+") || Integer.valueOf(inputString) < 1 
                                     || Integer.valueOf(inputString) > 50) {
        // No...
        System.err.println("Invalid entry (" + inputString + ") for Student "
                         + "amount! Try again...");
        inputString = "";  // Empty inputString so we loop again.
        System.out.println();
    }
}

// Valid amount provided.
int amount = Integer.valueOf(inputString);
String[] student = new String[amount];
int grade[] = new int[amount];

您马上就会注意到这里有一些明显的变化。整个 How many students do you have? 提示包含在 while 循环块中。如果用户未提供有效响应,则要求该用户重试。 studentgrade parallel arrays 仅在 学生人数 的有效响应后声明和初始化] 提供。

您还会注意到 while 循环条件不依赖于整数值,而是依赖于实际的字符串内容(不管它是什么)。如果变量为空 (""),则再次循环。这是因为 Scanner#nextLine() method is used to collect the Users input instead of the Scanner#nextInt() method. The prompt still expects an integer value to be supplied, just a string representation of an integer value and this is validated using the String#matches() method along with a small Regular Expression (regex).

出于多种原因,我个人更喜欢使用 Scanner#nextLine() 方法。我个人觉得它更灵活,特别是如果你想从一个提示中接受字母和数字输入。如果上面的提示是:

How many students do you have? (q to quit)

您只需要在数字验证码上方添加另一个 if 语句以查看是否提供了 'q' 或 'Q',例如:

// If either q or Q is entered then quit application.
if (amountString.matches("[qQ]")) {
    System.out.println("Bye-Bye");
    System.exit(0);
}

另外,matches()方法传递一个好的表达式,就不需要捕获异常来进行验证,不是说这有什么不妥,很多人都这样做,我特别不但是当我不需要这样做的时候。

旁注:我要在这里说明一个显而易见的事实,我相信你之前已经听过一百遍而且你听腻了,但是我再告诉你一次:

Your class methods should start with a lowercase letter (see Java Naming Conventions). I know you don't hear the compiler complaining but it does make it a little more difficult (at times) to read the code. Everyone that reads your code will appreciate you for it.

因为 studentgrade 数组是 parallel arrays 你会想要 minGrade()maxGrade( ) 方法将特定数组索引值 return 指定为最低或最高年级,以便可以对包含所确定的特定年级的学生建立引用关系。所以,这会更有用:

public static int minGrade(int[] arr, int size) {
    // Initialize min to have the highest possible value.
    int min = Integer.MAX_VALUE;
    int returnableIndex = -1;
    // loop to find lowest grade in array
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] < min) {
            min = arr[i];
            returnableIndex = i;
        }
    }
    return returnableIndex;
}

public static int maxGrade(int[] arr, int size) {
    int max = Integer.MIN_VALUE;
    int returnableIndex = -1;
    // loop to find highest grade in array
    for (int i = 0; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
            returnableIndex = i;
        }
    }
    return returnableIndex;
}

一切都在进行中,您的代码可能如下所示:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    // Number Of Students...
    String amountString = "";
    while (amountString.isEmpty()) {
        System.out.print("How many students do you have?: --> ");
        amountString = scan.nextLine().trim();
        
        // Is the supplied Number Of Students valid and within 
        // range (1 to 50 inclusive)?
        if (!amountString.matches("\d+") || Integer.valueOf(amountString) < 1
                || Integer.valueOf(amountString) > 50) {
            // No...
            System.err.println("Invalid entry (" + amountString + ") for Student "
                    + "amount! Try again...");
            amountString = "";  // Empty inputString so we loop again.
            System.out.println();
        }
    }
    
    // Valid amount provided.
    int amount = Integer.valueOf(amountString);

    // Declare and initialize parallel arrays
    String[] student = new String[amount];
    int grade[] = new int[amount];

    // Student Names and Grade...
    for (int i = 0; i < amount; i++) {
        // Student Name...
        String name = "";
        while (name.isEmpty()) {
            System.out.print("Enter student #" + (i + 1) + " name: --> ");
            name = scan.nextLine().trim();
            /* Is the name valid (contains upper or lower case letters from
               A-Z and a single whitespaces separating first and last name?
               Whitespace and last name is optional.         */
            if (!name.matches("(?i)([a-z]+)(\s{1})?([a-z]+)?")) {
                // No..
                System.err.println("Invalid Student #" + (i + 1) + " name ("
                        + name + ")! Try Again...");
                System.out.println();
                name = ""; // Empty name so we loop again.
            }
        }
        // Valid Student name provided...
        student[i] = name;

        // Student Grade...
        String gradeString = "";
        while (gradeString.isEmpty()) {
            System.out.print("Enter student #" + (i + 1) + " grade: --> ");
            gradeString = scan.nextLine().trim();
            // Is the supplied grade valid and within range (0 to 100 inclusive)?
            if (!gradeString.matches("\d+")
                    || Integer.valueOf(gradeString) < 0
                    || Integer.valueOf(gradeString) > 100) {
                // No...
                System.err.println("Invalid entry (" + gradeString + ") for "
                        + "Student #" + (i + 1) + " grade! Try again...");
                gradeString = "";
                System.out.println();
            }
        }
        // Valid Student grade provided...
        grade[i] = Integer.valueOf(gradeString);
    }

    // Display everyone's grade
    System.out.println();
    for (int i = 0; i < amount; i++) {
        System.out.println(student[i] + " received the final grade of " + grade[i]);
    }
    System.out.println();

    //Display who is highest and lowest...
    int index = maxGrade(grade, amount);
    System.out.println("The highest grade in the class was by '" + student[index]
            + "' with a grade of: " + grade[index]);

    index = minGrade(grade, amount);
    System.out.println("The lowest grade in the class was by '" + student[index]
            + "' with a grade of: " + grade[index]);


}                                         

public static int minGrade(int[] arr, int size) {
    // Initialize min to have the highest possible value.
    int min = Integer.MAX_VALUE;
    int returnableIndex = -1;
    // loop to find lowest grade in array
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] < min) {
            min = arr[i];
            returnableIndex = i;
        }
    }
    return returnableIndex;
}

public static int maxGrade(int[] arr, int size) {
    int max = Integer.MIN_VALUE;
    int returnableIndex = -1;
    // loop to find highest grade in array
    for (int i = 0; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
            returnableIndex = i;
        }
    }
    return returnableIndex;
}