I want my array of students to have their name and grade associated. So when I call on them after the fact I can display the top two performing students. This is homework So I don't need to have the whole code completed but I would like some help with making sure the inputs are properly stored. Right now my variables are x and i, x being the number of students, and i being the counter. Again my issues are with associating the grades of the students inputted with the names. I hope there is enough information.
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
int x = 0;
double average = 0;
int i = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please eneter how many students you have: ");
x = in.nextInt();
int students = 0;
int sum = 0;
int grades[] = new int[x];
String[] names = new String[x];
for(i = 0; i <= x; i++) {
System.out.println("Please enter student name: ");
String name = in.nextLine();
names[i] = name;
System.out.println("Grade: ");
int grade = in.nextInt();
grades[i] = grade;
students++;
sum += grade;
x++;
}
if(students>0) {
average = (double) sum/students;
}
System.out.println("The average is " + average);
System.out.println("There are " + students + " students");
System.out.println("The top two students are: " + grades);
}
}
The problem with your current code is that the for loop will never end, as you keep increasing the value of x, which is also used in the end condition.
Here are some suggestions:
Just store the number of students when you read it and remove the x variable:
int students = in.nextInt();
int grades[] = new int[students ];
String[] names = new String[students ];
Then read in this number of sudents:
for(i = 0; i < students; i++) {
To find the top two students you'd use the following logic (assumes 2 or more students)
if grade[0] >= grade[1]
max1 = 0
max2 = 1
else
max1 = 1
max2 = 0
for i from 2 to students-1
if grade[i] >= grade[max1]
max2 = max1
max1 = i
else if grade[i] > grade[max2]
max2 = i
The top two students are then at positions max1 and max2 in the names and grades array.
Probably overkill, but maybe someone will find it useful.
I store all the students in a TreeSet. I assume that each student has a unique name. I use a special Comparator to sort the students in the TreeSet according to their grades. A descending Iterator of the TreeSet will return the students from highest grade to lowest grade, so the first two items returned by this Iterator are the top two students.
import java.util.Comparator;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
/**
* A student name and her grade.
*/
public class StudentGrade {
/** Name of student. */
private String studentName;
/** Grade for this student. */
private int studentGrade;
/**
* Creates and returns instance of this class.
*
* #param name - student name
* #param grade - student grade
*/
public StudentGrade(String name, int grade) {
studentName = name;
studentGrade = grade;
}
/**
* #return Student's name.
*/
public String getStudentName() {
return studentName;
}
/**
* #return Student's rgade.
*/
public int getStudentGrade() {
return studentGrade;
}
/**
* Two instances of this class are equal if they both have the same name.
*/
#Override // java.lang.Object
public boolean equals(Object obj) {
boolean isEqual = false;
if (obj != null) {
Class<?> objClass = obj.getClass();
if (objClass.equals(getClass())) {
StudentGrade other = (StudentGrade) obj;
isEqual = studentName.equals(other.getStudentName());
}
}
return isEqual;
}
#Override // java.lang.Object
public int hashCode() {
return studentName.hashCode();
}
#Override // java.lang.Object
public String toString() {
return String.format("%s [%d]", studentName, studentGrade);
}
/**
* Start here.
*/
public static void main(String[] args) {
// Stores all student grades, sorted by grade in ascending order.
TreeSet<StudentGrade> studentSet = new TreeSet<>(new StudentGradeComparator());
Scanner in = new Scanner(System.in);
System.out.print("Please enter how many students you have: ");
int students = in.nextInt();
int index = students;
int sum = 0;
while (index > 0) {
// make sure we consume the newline character since 'nextInt()' does not
in.nextLine();
System.out.print("Enter student name: ");
String name = in.nextLine();
System.out.printf("Enter grade for %s: ", name);
int grade = in.nextInt();
sum += grade;
StudentGrade sg = new StudentGrade(name, grade);
studentSet.add(sg);
index--;
}
double average;
if (students > 0) {
average = (double) sum / students;
}
else {
average = 0.0d;
}
System.out.println("The average is " + average);
String verb = students == 1 ? "is" : "are";
String plural = students == 1 ? "" : "s";
System.out.printf("There %s %d student%s.%n", verb, students, plural);
if (students > 1) {
Iterator<StudentGrade> iter = studentSet.descendingIterator();
System.out.printf("The top two students are: %s, %s%n", iter.next(), iter.next());
}
}
}
/**
* Compares 'StudentGrade' instances according to their grades.
*/
class StudentGradeComparator implements Comparator<StudentGrade> {
/**
* Returns a positive number if 'sg1' grade is larger than that of 'sg2'.
* Returns a negative number if 'sg1' grade is less than that of 'sg2'.
* Returns zero if 'sg1' grade is equal to 'sg2' grade.
*/
#Override
public int compare(StudentGrade sg1, StudentGrade sg2) {
if (sg1 == null) {
if (sg2 != null) {
return -1;
}
else {
return 0;
}
}
else {
if (sg2 == null) {
return 1;
}
else {
return sg1.getStudentGrade() - sg2.getStudentGrade();
}
}
}
}
Here is a sample run:
Please enter how many students you have: 3
Enter student name: George
Enter grade for George: 70
Enter student name: Diego
Enter grade for Diego: 90
Enter student name: Edson
Enter grade for Edson: 65
The average is 75.0
There are 3 students.
The top two students are: Diego [90], George [70]
Related
I need to get the average test score from the numbers the user submitted and keep getting infinity. I need to know the average test score.
This is the student class:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
private ArrayList<Integer> scores;
public Student(String name){
this.name = name;
scores = new ArrayList<Integer>();
}
public String getName() {
return name;
} public void addQuiz(int score){
scores.add(score);
}
public double getTotalScore() {
for(int score : scores){
totalScore += score;
}
return totalScore;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
This is what i have for the main:
ArrayList<String> scores = new ArrayList<String>();
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
**student.addQuiz(Integer.parseInt(grade));**
//this is where the error is
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
double average = student.getTotalScore()/scores.size();
System.out.println("Average Quiz Score: " + student.getAverageScore());
This is the Output:
What is your name? b
Please enter your scores (q to quit): 95
95
95
q
Students Name: b
Total Quiz Scores: 285.0
Infinity
Average Quiz Score: Infinity
As you can see I get infinity even when dividing the scores by the size.
You need to make few changes in your code as shown below:
Student Class:
public class Student {
private String name;
private double totalScore;
private ArrayList<Integer> scores;
public Student(String name){
this.name = name;
scores = new ArrayList<Integer>();
}
public String getName() {
return name;
} public void addQuiz(int score){
scores.add(score);
}
public double getTotalScore() {
totalScore = 0;
for(int score : scores){
totalScore += score;
}
return totalScore;
}
public double getAverageScore(){
return getTotalScore()/scores.size();
}
}
Main Class:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// Request the name
System.out.print("What is your name?: ");
String name = input.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = input.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = input.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
}
Try to use this code, It will work correctly and display average score instead of Infinity.
Changes Done:
Removed private int numOfQuizzes; from Student class.
Added totalScore = 0; in getTotalScore() method in Student class.
Added return getTotalScore()/scores.size(); in getAverageScore() method in Student class. Here getTotalScore() with return total score and scores.size() will return total number of scores. (3 in case of your example)
Removed ArrayList<String> scores = new ArrayList<String>(); from Main class. As It is not needed in Main class.
Removed double average = student.getTotalScore()/scores.size(); because student.getAverageScore() in next line will calculate and return average value.
I think you've confused yourself holding onto two lists.
Remove the scores list in the main method. Also remove totalScore from the Student class; that is what is called a "calculated field"
Update the method
public double getTotalScore() {
double totalScore = 0;
for(int score : scores){
totalScore += score;
}
return totalScore;
}
Then you'll actually want a loop like this to more accurately handle ordering of input validation
String grade;
do {
grade = inp.nextLine();
if (grade.equals("q")) break;
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
} while (true);
Then, remove numOfQuizzes from the Student class.
In the average method, that's where you use
return getTotalScore()/scores.size();
You're currently getting Infinity twice because
The main method scores are never added to
You're never incrementing this.numOfQuizzes in the Student class
I'm having trouble making option 7 work in my code (i.e. choice == 7), the one that outputs a student's set of quiz scores.
When I run the program, it simply asks for jumps back to the original set of choices.
Any help would be much appreciated.
package studentquizgrades;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class StudentQuizGrades {
public static void main(String[] args) {
Map<String, Student> map = new HashMap<>();
addStudent(map);
}
private static void addStudent(Map<String, Student> map) {
Scanner userInput = new Scanner(System.in);
boolean finish = false;
do {
System.out.println("Please choose an option: ");
System.out.println("Add student and quizzes - 1, Get all quiz scores - 2, Get highest quiz score- 3, ");
System.out.println("Get lowest quiz score - 4, Get class average - 5, View a list of all students - 6");
System.out.println("Get a student's quiz scores - 7, Quit - 8");
int choice = userInput.nextInt();
if (choice == 1) {
Set<String> keySet = map.keySet();
System.out.println("How many students would you like to add?");
int numberOfStudents = userInput.nextInt();
for (int counter = 0; counter < numberOfStudents; counter++) {
System.out.println("ENTER NAME");
Scanner addName = new Scanner(System.in);
String name = (addName.nextLine());
System.out.println("Enter First Quiz Score");
Scanner addQuiz1 = new Scanner(System.in);
int quiz1 = (addQuiz1.nextInt());
System.out.println("Enter Second Quiz Score");
Scanner addQuiz2 = new Scanner(System.in);
int quiz2 = (addQuiz2.nextInt());
System.out.println("Enter Third Quiz Score");
Scanner addQuiz3 = new Scanner(System.in);
int quiz3 = (addQuiz3.nextInt());
Student student = new Student(name, quiz1, quiz2, quiz3);
map.put(student.getKey(), student);
}
} else if (choice == 2) {
Set<String> keySet = map.keySet();
for (String currentKey : keySet) {
Student student = map.get(currentKey);
System.out.println();
System.out.println(currentKey);
System.out.println(Arrays.toString(student.getQuizGrades()));
System.out.println();
}
} else if (choice == 3) {
Set<String> keySet = map.keySet();
int max = 0;
String maxName = null;
for (String currentKey : keySet) {
Student student = map.get(currentKey);
int[] scores = student.getQuizGrades();
for (int counter = 1; counter < scores.length; counter++) {
if (scores[counter] > max) {
max = scores[counter];
maxName = currentKey;
}
}
}
System.out.println();
System.out.println("The highest quiz score was " + max + "; his/her name is " + maxName);
System.out.println();
} else if (choice == 4) {
Set<String> keySet = map.keySet();
int min = Integer.MAX_VALUE;
String minName = null;
for (String currentKey : keySet) {
Student student = map.get(currentKey);
int index = 0;
int[] scores = student.getQuizGrades();
for (int counter = 0; counter < scores.length; counter++) {
if (scores[counter] < min) {
minName = currentKey;
min = scores[counter];
}
}
}
System.out.println();
System.out.println("The lowest quiz score was " + min + "; his or her name is " + minName);
System.out.println();
} else if (choice == 5) {
Set<String> keySet = map.keySet();
int[] allGrades;
int sum = 0;
int counter2 = 0;
for (String currentKey : keySet) {
Student student = map.get(currentKey);
int[] scores = student.getQuizGrades();
for (int counter = 0; counter < scores.length; counter++) {
int j = scores[counter];
sum = sum + j;
counter2++;
}
}
int average = sum / counter2;
System.out.println("");
System.out.println("The class average is: " + average);
System.out.println("");
} else if (choice == 6) {
Set<String> keySet = map.keySet();
System.out.println("");
System.out.println("List of students: ");
for (String currentKey : keySet) {
Student student = map.get(currentKey);
System.out.println(currentKey);
}
}
else if(choice == 7){
Set<String> keySet = map.keySet();
System.out.println("");
System.out.println("Please enter a student's name: ");
String studentName = userInput.nextLine();
for (String currentKey : keySet) {
Student student = map.get(currentKey);
if(studentName == currentKey){
System.out.println(currentKey + "'s quiz scores:");
int [] quizArray = student.getQuizGrades();
for(int counter1 = 0; counter1 < quizArray.length; counter1++ ){
System.out.println(quizArray[counter1]);
}
}
}
}
else if (choice == 8) {
finish = true;
break;
}
} while (finish == false);
}
}
package studentquizgrades;
public class Student {
private String key;
private int grade1;
private int grade2;
private int grade3;
public Student(String key, int grade1, int grade2, int grade3){
this.key = key;
this.grade1 = grade1;
this.grade2 = grade2;
this.grade3 = grade3;
}
public String getKey(){
return key;
}
public int[] getQuizGrades(){
int [] anArray = {grade1, grade2, grade3};
return anArray;
}
public int getAverageScore(){
int average = (grade1 + grade2 + grade3)/3;
return average;
}
}
You mix scanner.nextInt() and scanner.nextLine().
When you call scanner.nextInt() and then you call scanner.nextLine(), scanner.nextLine() returns the remain of the current line of the input entered by scanner.nextInt(), that is an empty String. And that before you may enter anything.
That's why you loop to the original set of choices.
You should avoid to chainnext() and nextLine(). Try to use only the one or the other one.
Besides, the code in the else if(choice == 7) block compares String values with == and besides this comparison is even not required since you perform a loop on the map of students to retrieve the student while you have a Map that may retrieve the information in a straight way :
Set<String> keySet = map.keySet();
System.out.println("");
System.out.println("Please enter a student's name: ");
String studentName = userInput.next();
for (String currentKey : keySet) {
Student student = map.get(currentKey);
if(studentName == currentKey){
System.out.println(currentKey + "'s quiz scores:");
int [] quizArray = student.getQuizGrades();
for(int counter1 = 0; counter1 < quizArray.length; counter1++ ){
System.out.println(quizArray[counter1]);
}
}
}
You could do simply :
System.out.println("");
System.out.println("Please enter a student's name: ");
String studentName = userInput.next();
Student student = map.get(studentName);
if (student!=null){
System.out.println(studentName + "'s quiz scores:");
int[] quizArray = student.getQuizGrades();
for (int counter1 = 0; counter1 < quizArray.length; counter1++) {
System.out.println(quizArray[counter1]);
}
}
Instead of if (studentName == currentKey) use if (studentName.equals(currentKey). You should always compare strings with equals(...), because == only checks the equality of references, not the objects itself. As studentName and current key are two independent instances, they are never equal in a comaprison with == as their references differ.
You should try to refactor your code, as there are multiple issues. As #markspace already pointed out, your loop is unnecessary and the critical if statement is not needed at all.
for (String currentKey : keySet) {
Student student = map.get(currentKey);
if(studentName == currentKey){
//...
}
}
This can be reduced to the following code as you deal with a map. That is the point of a map, not having to iterate through all elements, but to use a key to directly access an element.
Student student = map.get(currentKey);
if (student != null) {
// ...
}
Also, you should call nextLine(); after int choice = userInput.nextInt(); (and other next...(...); calls), because they do not consume the newline character. Otherwise studentName = userInput.nextLine(); will only contain the newline character leftover from last call to nextInt()...;.
I am working on a project in Java that requests user inputs information like name, id, score in array.I need to help about calculate a average grade that user input and how to find out who have highest score. Here is my code:
package finalproject;
import java.util.Scanner;
public class FinalProject {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Cis84[] student = new Cis84[50];
int option;
for (int c = 0; c < 50; c++)
student[c] = new Cis84();
do {
System.out.print("");
System.out.println("1) Add Information");
System.out.println("2) Show report");
System.out.println("3) Exit");
System.out.print("\nEnter option: ");
option = input.nextInt();
switch (option) {
case 1:
String n;
double g;
int index,
i;
System.out.println("Which position of the student?");
index = input.nextInt();
System.out.println("What is the student's name:");
n = input.nextLine();
n = input.nextLine();
System.out.println("What is student's Id");
i = input.nextInt();
System.out.println("What is student's score");
g = input.nextDouble();
student[index].setName(n);
student[index].setGrade(g);
student[index].setId(i);
break;
case 2:
for (int c = 0; c < 50; c++)
System.out.println(student[c]);
break;
case 3:
System.out.println("You are done");
break;
default:
System.out.println("Try again");
break;
}
} while (option != 3);
}
}
and class
package finalproject;
public class Cis84 {
private String name;
private int id;
private double grade;
public Cis84() {
name = "not input yet";
id = 00000;
grade = 0.0;
}
public Cis84(String n, int i, double g) {
name = n;
id = i;
grade = g;
}
public void setName(String n) {
name = n;
}
public void setId(int i) {
id = i;
}
public void setGrade(double g) {
grade = g;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public double getGrade() {
return grade;
}
public String toString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
}
This is for homework, clearly, and I don't feel comfortable giving you a straight answer. However, what you will want to do is when it is time to display the averages, go through the entire students array and sum up the scores, then divide by the size of the array, likely using a for loop. You could keep track of the size of the array by having a counter increased anytime option 1 of the switch-case is called.
To find the highest score, you should be able to use the average-calculation for loop mentioned above, and check the grade against the previous highest grade. Record the index of whichever has the highest grade and print it out.
Have some pseudocode!
for(size of array which isn't NULL){
add indexed grade to sum;
check to see if this index has the highest grade;
}
display (sum/size); //the average
display highest grade;
calculating average would be something like the below code. Remember, average is the sum of all the values divided by the total number of values
double sum = 0, divisor = 0;
for (int k = 0; k < student.length; k++){
sum += student[k].getGrade();//add up all the grades
divisor = k;//get the number of total items
}
return sum/divisor; //divide
private static double calculateAverage(Cis84[] students) {
double sum = 0;
for (Cis84 student : students) {
sum += student.getGrade();
}
return sum / students.length;
}
private static double calculateHighestScore(Cis84[] students) {
double highestScore = 0;
for (Cis84 student : students) {
if (student.getGrade() > highestScore) {
highestScore = student.getGrade();
}
}
return highestScore;
}
Then, to show the information:
case 2:
System.out.println("Average:");
System.out.println(calculateAverage(student));
System.out.println("Highest score:");
System.out.println(calculateHighestScore(student));
I have my code working right, the only problem is that my output isn't correct because I can't find the right place to set the array of numbers back to zero. The basis of the programs is to take in data that contains names with corresponding grades. My output should follow this criteria:
Alice [87, 99, 96, 99, 86, 96, 77, 95, 70, 88]
Name: Alice
Length: 10
Average: 89.30
Median: 91.5
Maximum: 99
Mininum: 70
I get the first person's results correct, however, the ones that follow are incorrect because they contain all of the values being read in for every person. So, the next person will have "Alice's" grades plus their own when my code performs operations on the array for that person. I have two programs, the first is the main program that reads the data in and calls the methods to print and operate. The second is the class with all the methods that perform the operations.
This is the main program:
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
sgrades = null;
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
grades = null;
}
}
I've tried adding place to erase the values of the array for the next person by setting it to null. I've had no luck with this.
This is the next program, which contains the methods.
public class Grades {
private String studentName; // name of course this GradeBook represents
private int[] grades; // array of student grades
/**
* #param studentName The name of the student.
* #param grades The grades for the student.
*/
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
} // end two-argument GradeBook constructor
/**
* Method to convert array to a string and print.
*
* #return The name of the student with array of grades.
*/
public String toString() {
return (String) studentName + " " + Arrays.toString(grades);
}
/**
* One-argument constructor initializes studentName.
* The grades array is null.
*
* #param name The name of the student.
*/
public Grades(String name) {
studentName = name; // initialize courseName
} // end one-argument Grades constructor
/**
* Method to set the student name.
*
* #return The name of the student.
*/
public String getName() {
return studentName;
} // end method getCourseName
/**
* Method to set the length of the amount of grades.
*
* #return Number of grades for student.
*/
public int length() {
return grades.length;
}
/**
* Determine average grade for grades.
*
* #return the average of the grades.
*/
public double average() {
double total = 0; // initialize total
double average = 0.0;
// sum grades for one student, while loop
int index = 0;
while (index < grades.length) {
int grade = grades[index]; // get grade at index
total += grade;
index++; // need to increment
}
average = total / grades.length;
// return average of grades
return (double) average;
} // end method getAverage
/**
* Determine median grade for grades.
*
* #return the median of the grades.
*/
public double median() {
Arrays.sort(grades); //sort grades array
double median = 0.0;
if (grades.length%2 == 0) //checks to see if amount of grades is even/odd
//this is median if list of grades is even
median = ((double)grades[grades.length/2-1] + (double)grades[grades.length/2])/2;
else
//this is median if list of grades is odd
median = (double) grades[grades.length/2];
return (double) median;
}
/**
* Find minimum grade.
*
* #return the minimum grade.
*/
public int minimum() {
int lowGrade = grades[0]; // assume grades[0] is smallest
// loop through grades array, for loop
for (int index = 0; index < grades.length; index++) {
int grade = grades[index]; // get grade at index
// if grade lower than lowGrade, assign it to lowGrade
if (grade < lowGrade)
lowGrade = grade; // new lowest grade
} // end for
return lowGrade; // return lowest grade
} // end method getMinimum
/**
* Find maximum grade.
*
* #return the maximum grade.
*/
public int maximum() {
int highGrade = grades[0]; // assume grades[0] is largest
// loop through grades array, for-each loop
for (int grade : grades) {
// if grade greater than highGrade, assign it to highGrade
if (grade > highGrade)
highGrade = grade; // new highest grade
} // end for
return highGrade; // return highest grade
} // end method getMaximum
}
My main question is, how can I "refresh" the array for every new student that I read in?
You're looking for gradeList.clear(). But why are you copying everything from gradeList to sgrades? Seems kind of redundant.
import java.util.Scanner;
import java.util.Arrays;
class StudentScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the # of students");
int numOfStudents = input.nextInt();
int[] scores = new int[numOfStudents];
String[] names = new String[numOfStudents];
for (int i = 0; i < numOfStudents; i++) {
input.nextLine();
System.out.print("Enter name: ");
names[i] = input.nextLine();
System.out.print("Enter score: ");
scores[i] = input.nextInt();
}
// This doesn't sort anything, it just prints out the result in unsorted way
/*for (int i = 0; i < numOfStudents; i++) {
System.out.println(names[i] + " " + scores[i]);
}*/
Arrays.sort(scores);
reverse(scores);
for (int u: scores) {
System.out.println(u);
}
}
public static int[] reverse(int[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
The original question is:
Write a program that prompts the user to enter the number of students, the students’ names, and their scores, and prints student names in decreasing order of their scores.
My question is how do you display the name with the sorted list of scores?
You necessarily don't have to give me a complete solution, just give me a hint so I can solve it myself.
You can encapsulate the related fields into a class, e.g. a StudentRecord can encapsulate the fields name and score.
Now, you sort a collection of these objects based on the second field, score. When it comes time to print the sorted result, you iterate through the collection and print the first field, name.
To illustrate:
public class StudentRecord implements Comparable<StudentRecord> {
private String name;
private int score;
public StudentRecord(String name, int score) {
this.name = name;
this.score = score;
}
#Override
public int compareTo(StudentRecord other) {
if (score == other.score) return 0;
else if (score < other.score) return -1;
else return 1;
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
StudentRecord stu1 = new StudentRecord("Matt", 50);
StudentRecord stu2 = new StudentRecord("John", 90);
if (stu1.compareTo(stu2) == 0) {
System.out.println(stu1.toString() + " has the same score with " + stu2.toString());
}
else if (stu1.compareTo(stu2) < 0) {
System.out.println(stu1.toString() + " has a lower score than " + stu2.toString());
}
else {
System.out.println(stu1.toString() + " has a higher score than " + stu2.toString());
}
// output:
// Matt has a lower score than John
}
}
In many sorting algorithms, implementing the Comparable interface gives the algorithm enough information to sort a collection of such objects implementing said interface.
You're not going to be able to use Arrays.sort() for this problem because you need to sort both arrays together. Write a sorting function that sorts the scores in order, and every time it swaps two scores, swap the students with those scores as well.