0

我正在尝试做的是搜索“gradePsd”数组找到最高成绩,如果有两个成绩相同,则打印学生的姓名以进行控制台。

我遇到的问题是这种方法正在获取数组的第一个索引值并打印它,因为它是第一遍的高值,如果第二个值大于第一个值,那么它也会打印等等.

所以我的问题是我怎样才能让它打印出高分的学生。

public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
    String nameRtn = "";
    int num = gradePsd[0];

    System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");

    for (int  i = 0; i < gradePsd.length;  i++)
    {
        if (gradePsd[i] >= num)
        {
            num = gradePsd[i];
            nameRtn = NamePsd[i]; 
        }

        System.out.print(nameRtn + ", ");
    }
}
4

2 回答 2

0

num用 -1初始化并System.out退出 for 循环。但是您只能使用您的代码确定一名学生。如果要存储多个名称,则需要nameRtn成为 a 。Collection

像这样的东西:

public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) {
    Collection<String> namesRtn = new ArrayList<String>();
    int num = -1;

    for (int  i = 0; i < gradePsd.length;  i++) {
        if (gradePsd[i] > num) {
            num = gradePsd[i];
            namesRtn.clear();  // clear name list as we have a new highest grade
            namesRtn.add(NamePsd[i]);  // store name in list
        } else if (gradePsd[i] == num) {
            namesRtn.add(NamePsd[i]);  // if a second student has the same grade store it to the list
        }

    }
    System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are: " + namesRtn);
}
于 2012-12-06T12:13:25.617 回答
0

首先找到最大的数字,然后打印具有该数字的学生

public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
    {

    String nameRtn = "";
    int num = gradePsd[0];

     System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
    //find the highest number
    for (int  i = 0; i < gradePsd.length;  i++){
    if (gradePsd[i] >= num){
        num = gradePsd[i];
    }
    //print students with that number
    for (int  j = 0; j < NamePsd.length;  j++){
        if (gradePsd[j] == num)
        {
            nameRtn = NamePsd[j]; 
            System.out.print(nameRtn + ", "); 
        }
    }

可能的 1000 个解决方案之一。

于 2012-12-06T12:14:19.000 回答