Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have been working on this program for the past couple of days and know exactly what I want to do, just not how to go about doing it. Basically I have two arrays, one a string containing student names, the other array an int containing student scores. Both arrays values are inputs entered by the user. Ultimately I am wanting to print out the corresponing names and scores in descending order from highest score to lowest. Now, my problem lies toward the end of the code where I can't for the life of me figure out how to make the two indexes match for println purposes (I have commented where the issue lies. I have the scores printing in desceding order from highest to lowest, but I can't get the names to comply. Any advice on how to solve this issue would be appreciated.

import java.util.Scanner;

public class TestArray
{
    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter the number of students in your class: ");
        int number = input.nextInt();

        System.out.println("Now enter the " + number + " students names");
        String[] nameList = new String[number];

        for (int i = 0; i < number; i++) {
            nameList[i] = input.next();
        }

        System.out.println("Next, enter the score of each student: ");
        int[] numGrades = new int[number];
        for (int i = 0; i < number; i++) {
            numGrades[i] = input.nextInt();
        }

        for (int i = 0; i < number; i++) {
            int currentMax = numGrades[i];
            int currentMaxIndex = i;
            int currentNameIndex = i;

            for (int j = i + 1; j < number; j++) {
                if (currentMax < numGrades[j]) {
                    currentMax = numGrades[j];
                    currentMaxIndex = j; // index max
                    currentNameIndex = j;
                }
            }

            if (currentMaxIndex != i) {
                numGrades[currentMaxIndex] = numGrades[i];
                numGrades[i] = currentMax;
            }

            if (currentNameIndex != i) {
                nameList[currentNameIndex] = String.valueOf(nameList[i]);
                // need nameList[i] to = the current index of the numGrades array HOW???
            }
        }

        for (int i = 0; i < number; i++) {
            System.out.println(nameList[i] + " had a score of " + numGrades[i]);
        }
    }
}
share|improve this question
2  
If you've learned classes, yet, it would be better to put the score and name inside of a class and use a single array of objects of that class. –  ValekHalfHeart Oct 20 '13 at 2:45

4 Answers 4

up vote 3 down vote accepted

In order for this to work, you must keep the arrays synchronized. When you move a grade, you must move the corresponding name in the exact same way, so that the array of names and the array of grades is always coordinated.

You may understand that already, it is hard to tell from the code. If so, you will need to either do the name move within the same block ({}) as does the grade move, which would make the most sense, or you need to store the necessary integer(s) somewhere so another block can use them.


addition to answer:

you have two arrays with values like

peter    45
alice    53
garth    50

(we'll hope it isn't an exam with 100 points)

You are sorting the second array; your maximum value, etc., all have to do with the scores in that array.

Let's say you reach the point where you are going to swap garth's score with alice's score. You will, in some variables or other, have a value for 2 for garth and 1 for alice, and you will put 50 in a temp var, put alice's 53 in position2, and put garth's 50 in position 1.

What you have to do is use those SAME indices to move the names, so you put garth in position 1 and alice in position 2. After you're done, you have:

peter   45
garth   50
alice   53

You don't need any additional variables for positions of strings; you need to put the strings into the same positions in the string array as the scores you are moving in the scores array.

share|improve this answer
    
Thanks for you reply rcook. What you say makes sense and for the most part is what I was doing. I am just having a hard time dailing in how to get that string index to equal the integer one because there is no way that I can see to make a max value for the string array values like I did with the int array values. –  censortrip Oct 20 '13 at 3:03

There are two ways to go around this, one is you can use a Map class to hold the name value pairs corresponding to Student Names and Scores. You'd need to see javadoc for Map interface and its implementing classes (e.g. HashMap). You'd declare it like this:

Map<String, Integer> nameGradeMap = new HashMap<String, Integer>(); 

Afterwords, sort the keys and values of the hashmap. This can be done with a call to Collections.sort() method.

The second option is to encapsulate both student name (String) and grade (Integer) as instance variable of some class, e.g. Student. Then use a custom comparator to implement ordering by names, and then by scores. You'd need to read the javadoc for Comparable interface and see some examples on how to use it. Again you'd sort them using a call to Collections.sort(). I guess this should be enough things for you to look up to get you started.

share|improve this answer
    
Thanks for the advice, I'll definitely check it out and see if I can solve my issue. –  censortrip Oct 20 '13 at 3:05

It appears you have some sorting implementation going on so here's what I suggest.


1. When you get the students and grades into different arrays, they should match up by index, which I believe you did.


2. In you sorting implementation, when you sort the array of grades, for every grade index you swap, do the same for the names array index. That will keep your indices of the two arrays the same as far as matching pairs

if(currentMaxIndex != i){        
       numGrades[currentMaxIndex] = numGrades[i];
       numGrades[i] = currentMax; 
       // also swap the student name indices                      
       // you indices should be the same for both arrays                                     
}
//you don't need the other if statement, because you are swapping in the one above

In your loops, currentNameIndex should equal currentMaxIndex, so you really don't need currentNameIndex. When you're swapping in your if statement, use the currentMaxIndex for both array swaps.

Edit: with swap

// Simple swap
int n = 1;
int n1 = 2;

int temp = n;  // temp holds value of n (1)
n = n1;  // now n = 2
n1 = temp  // now n1 = 1

The swap example above, do the same with your names array, using the currentMaxIndex

share|improve this answer
    
Thanks for the reply peeskillet, I did do your first suggestion and tried to do the same for the 2nd, however, I don't know how to get the name arrays index to swap with the int array. That is the whole problem I am having. –  censortrip Oct 20 '13 at 2:59
    
See my edit with example swap –  peeskillet Oct 20 '13 at 3:04
1  
When you sort the grades just also sort the names. If you swap grades[4] with grades[8] also swap names[4] with names[8]. However you are sorting the grades, just also sort the names side by side. –  Radiodef Oct 20 '13 at 3:05
    
@Radiodef Much simpler explaination –  peeskillet Oct 20 '13 at 3:06

Just for future reference, here is the solution I came up with that worked. Note that I only altered the last section of code and just included that section below. Thanks for all of those who helped me with this.

    (int i = 0; i < number; i++){ 
      int currentMax = numGrades[i];
      int currentMaxIndex = i;            
      int currentNameIndex = i;
      String currentName = nameList[i];

      for (int j = i + 1; j < number; j++){
         if(currentMax < numGrades[j] ){
            currentMax = numGrades[j];    
            currentMaxIndex = j;                 
            currentNameIndex = j;
            currentName = nameList[j];
          }           
      }

         if(currentMaxIndex != i){         
           numGrades[currentMaxIndex] = numGrades[i];
           numGrades[i] = currentMax;                                                         
           nameList[currentNameIndex] = String.valueOf(nameList[i]);
           nameList[i] = String.valueOf(currentName);        
      }

      }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.