I have a simple question about my code. I’m quite new to java and trying to self learn but im kind of stuck on loops right now. To me it seems like this should work. The problem is too ask for a number of students, then have the user input the names and scores of each student. Then it should display the first and second highest scoring students. For some reason my code just shows the first name and score I enter for both the first highest score and the second highest score. I probably made some big mistake but maybe somebody can point me in the right direction? Sorry if this looks like a huge mess. 🙁
public class Chapter4_9 {
public static void main(String[] args) {
//scanner for input
Scanner input = new Scanner(System.in);
//ask user for number of students
System.out.print("Enter the number of students: ");
int numberStudents = input.nextInt();
//declare variables
double highestScore = 0;
double tempScore = 0;
double secondHighestScore = 0;
String firstStudent = "";
String tempStudent = "";
String secondStudent = "";
for (int i = 0; numberStudents != i; ++i) {
System.out.print("Enter the students name followed by his score: ");
String studentName = input.next();
double studentScore = input.nextDouble();
if (i == 0){
firstStudent = studentName;
highestScore = studentScore;
}
else if (studentScore > highestScore) {
tempStudent = firstStudent;
studentName = firstStudent;
secondStudent = tempStudent;
tempScore = highestScore;
studentScore = highestScore;
secondHighestScore = tempScore;
}
}
System.out.println("The highest scoring student is " + firstStudent + " with a " + highestScore);
System.out.println("The second highest scoring student is " + secondStudent + " with a " + secondHighestScore);
}
}
This block seems a little muddled:
What is the intended consequence of this block? Why are you overwriting the value of
studentNameandstudentScore, when they’re never read again (before you read new values from the user anyway)?Presumably the aim is to replace the second score/name with the highest score/name, and then replace the highest ones with the current input – but that’s not what the code does at all. This would do it:
No need for temporary variables at all.
However, just that change isn’t enough. You also need to consider the situation where the new score isn’t higher than the current highest score, but is higher than the current second highest score. I’ll leave you to work out what that requires…
By the way, your code would probably be simpler if you introduced a separate class for the “name/score” combination, e.g.
Student. Then you wouldn’t have parallel variables – you’d just havetopStudent,secondStudent,currentStudentto worry about.