meorasso
meorasso

Reputation: 9

Double printing in an array data structure

I am having a hard time with my results. It was supposedly to print the highest and lowest grade of the person but it turns out it prints the same who had the highest score.

Output:

Highest : Doyoung, 100

Lowest : Doyoung, 100

and also it changes the showAllStudent Data and the grade.

Output:

1. Doyoung - 100 - FAILED

2. Ramburat - 100 - PASSED

Source code for Highest and Lowest

public static void highestLowest ()
{
    int max_index = 0;
    int min_index = 0;
    
    // Loop from index 0 to count of arrays
    for(int i=0; i<count; i++)
    {
        // Check for the index of max grade
        if(grade[i] > grade[max_index])
            grade[max_index] = grade[i];
        // Check for the index of min grade
        if(grade[i] < grade[min_index])
            grade[min_index] = grade[i];
    }
    
    System.out.println("Highest : " + name[max_index] + ", " + grade[max_index]);
    System.out.println("Lowest : " + name[min_index] + ", " + grade[min_index]);
    
    
}

Source code for ShowAllStudent Data

 public static void showAllStudents()
{
    // if count is 0 then no students in the list
    if(count == 0)
    {
        System.out.println("There are no registered student in ISCP");
    }
    else
    {
        // Loop from index 0 to count of arrays
        for(int i=0; i<count; i++)
        {
            System.out.println(i+1+". " + name[i] + " - " + grade[i] + " - " + result[i]);
        
        }
    }
}

Source code for static void main

 public static void main (String [] args)
{
    

    enlistStudent("Doyoung", 50);
    enlistStudent("Ramburat", 100);

    
    
    highestLowest();

    showAllStudents();  

}

Upvotes: 0

Views: 18

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201517

You are updating grade instead of the min and max indices. This

// Check for the index of max grade
if(grade[i] > grade[max_index])
    grade[max_index] = grade[i];
// Check for the index of min grade
if(grade[i] < grade[min_index])
    grade[min_index] = grade[i];

Should be

// Check for the index of max grade
if(grade[i] > grade[max_index])
    max_index = i;
// Check for the index of min grade
if(grade[i] < grade[min_index])
    min_index = i;

Upvotes: 1

Related Questions