I'm stuck on this program. I need to write a program that has you enter in the number of students, and then type in their name and score. It outputs the name and score sorted from greatest to least. You have to use single dimensional strings. I am able to read it all, store it, then sort the numbers from least to greatest, reverse that to greatest to least but I can't figure out how to attach the names to the scores.

Enter number of students: 3 Smith 70 Jones 30 Peterson 100//The output isPeterson 100 Smith 70 Jones 30

Here is my half finished code if any of it makes sense:

import java.util.Scanner;

public class JavaApplication46 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter number of students: ");

int numOfStu = input.nextInt();

int[] grades = new int[numOfStu];

String[] names = new String[numOfStu];

int grade = 0;

String name = "";

for(int i = 0; i < numOfStu; i++){

name = input.next();

grade = input.nextInt();

names[i] = name;

grades[i] = grade;

System.out.println("");

}//this is the area that sorts it from least to greatest

//i is the indexed value of the last number in array

//if it's 10 numbers big, i is 9

//loop ends before index 0 because 0 should be in it's place at the end already

for(int i = grades.length - 1; i > 0; i--){

//resets both to 0 to start at the beginning of the array

//so that you can test the new first number

int currentMax = grades[0];

int currentMaxIndex = 0;

//finds largest number out of all up to back-limit

//i is back-limit that gets chopped off by one each time

for (int k = 1; k <= i; k++){

if (currentMax < grades[k]){

currentMax = grades[k];

currentMaxIndex = k;

}

}

//after largest number is found, assign that number to i

//i is a high number like 9, then 8, then 7, etc.

//each time it runs, i-- so each second highest max number

//gets put infront of the all time highest number

grades[currentMaxIndex] = grades[i];

grades[i] = currentMax;

}

}

public static int[] reverseInt(int[] array) {

int[] poop = new int[array.length];

for(int i =0, j = poop.length -1; i < array.length; i++, j-- ) {

poop[j] = array[i];

}

return poop;

}

}

Log in to comment