java数组显示最低学生

标签 java

我有这个程序,要求用户输入学生及其分数。然后显示得分最高和最低的学生姓名。我的问题是我的程序不会打印最低分数。

任何帮助将不胜感激。 下面是我的代码。

private Scanner n;
private int limit;
private String[] names;
private int[] scores;

public Exercise9() {

    n = new Scanner(System.in);
    limit = 0;

    index();
}

public void index() {

    int counter = 0;

    System.out.print("Enter how many students : ");
    limit = Integer.parseInt(n.nextLine());

    names = new String[limit];
    scores = new int[limit];

    while(counter < limit && limit != 0) {

        System.out.print("Enter name : ");
        names[counter] = n.nextLine();

        System.out.print("Enter score : ");
        scores[counter] = Integer.parseInt(n.nextLine());

        counter += 1;

    }

    if(limit == 0) {
        System.out.print("\n\nNo student(s) to display .");
    } else {
        displayStudents();
    }
}

public void displayStudents() {

    System.out.print("\n\nDisplay list of student(s) and scores : \n");

    for(int x = 0 ; x < limit ; x++) {
        System.out.println("\t" + names[x] + "\t" + scores[x]);
    }

    System.out.print("\n\nHighest : " + getHighest() + "\t\tLowest : " + getLowest());
}

public String getHighest() {

    int theScore = 0;
    String theName = "";

    for(int x = 0 ; x < scores.length; x++) {
        if(scores[x] > theScore) {
            theScore = scores[x];
            theName = names[x];
        }
    }
    return theName;
}

public String getLowest() {

    int theScore = 0;
    String theName = "";

    for(int x = 0 ; x < scores.length; x++) {
        if(scores[x] < theScore) {
            theScore = scores[x];
            theName = names[x];
        }
    }
    return theName;
}

public static void main(String[] args) {

    new Exercise9();
}

最佳答案

您首先在 getLowest() 中将变量 theScore 初始化为零。假设您不会获得负分,则该分数永远不会更新。

尝试将 theScore 初始化为任意高的数字。

关于java数组显示最低学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882960/

相关文章:

java - 在哪里放置 Java Web 应用程序的驱动程序

java - 解码原始字节数组后如何更改特定字段值?

java - 创建数组编译时间?

java - 将 FindBugs 配置从 Sonar 导入 Maven

java - Java 7 上的 Swing Nimbus LoweredBorder

java - Android Json 解析与 multipartEntity

java - Android Textview变黑了

java - Liferay 产生异常 : null and javax. servlet.ServletException : java. lang.StackOverflowError

Javadoc 正在消失

java - 使用java数据库连接从MS Access表中删除指定记录