我有一个关于我的代码的简单问题。我对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);
}
}
最佳答案
这个 block 看起来有点困惑:
else if (studentScore > highestScore) {
tempStudent = firstStudent;
studentName = firstStudent;
secondStudent = tempStudent;
tempScore = highestScore;
studentScore = highestScore;
secondHighestScore = tempScore;
}
此 block 的预期结果是什么?为什么要覆盖 studentName
和 studentScore
的值,因为它们再也不会被读取(无论如何,在您从用户那里读取新值之前)?
大概目标是用最高分数/名称替换第二个分数/名称,然后用当前输入替换最高分数/名称 - 但这根本不是代码所做的。这样就可以了:
secondStudent = firstStudent;
secondScore = highestScore;
firstStudent = studentName;
highestScore = studentScore;
根本不需要临时变量。
但是,仅仅这样的改变还不够。您还需要考虑新分数不高于当前最高分数,但高于当前第二高的情况分数。我会让你自己弄清楚需要什么......
顺便说一句,如果您为“名称/分数”组合引入一个单独的类,例如,您的代码可能会更简单学生
。那么你就不会有并行变量 - 你只需担心 topStudent
、secondStudent
、currentStudent
即可。
关于java - 一个关于java循环的简单程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807052/