我对我的代码有一个简单的问题。我对java很陌生,并试图自学,但我现在有点陷入循环。对我来说,这似乎应该有效。问题是要求一些学生,然后让用户输入每个学生的姓名和分数。然后它应该显示得分最高的学生和第二高的学生。出于某种原因,我的代码只显示了我为第一高分和第二高分输入的名字和分数。我可能犯了一些大错误,但也许有人可以指出我正确的方向?对不起,如果这看起来像一个巨大的混乱。:(
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);
}
}