java - 一个关于java循环的简单程序问题

标签 java loops

我有一个关于我的代码的简单问题。我对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 的预期结果是什么?为什么要覆盖 studentNamestudentScore 的值,因为它们再也不会被读取(无论如何,在您从用户那里读取新值之前)?

大概目标是用最高分数/名称替换第二个分数/名称,然后用当前输入替换最高分数/名称 - 但这根本不是代码所做的。这样就可以了:

secondStudent = firstStudent;
secondScore = highestScore;
firstStudent = studentName;
highestScore = studentScore;

根本不需要临时变量。

但是,仅仅这样的改变还不够。您需要考虑新分数不高于当前最高分数,但高于当前第二高的情况分数。我会让你自己弄清楚需要什么......

顺便说一句,如果您为“名称/分数”组合引入一个单独的类,例如,您的代码可能会更简单学生。那么你就不会有并行变量 - 你只需担心 topStudentsecondStudentcurrentStudent 即可。

关于java - 一个关于java循环的简单程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807052/

相关文章:

java - 微服务:我应该按实体还是按 MVC 模式结构来安排 Spring 项目结构?

java - 在 Eclipse IDE 中使用 Java 中的 IO 流时文件将位于何处?

matlab - 在 Matlab 中将一个矩阵复制到另一个矩阵

Java嵌套for循环

java - 在 Java 中使用字符串替换方法时遇到问题

java - Junit 4如何在测试套件中初始化并将其传递给测试类

java - Spring security Remember-me 无法正常工作,数据库表无法正常工作

shell - 以特定频率循环 VxWorks 中的命令

javascript - 如何将背景动画制作成循环(重复功能)

loops - loop 和 while true 有什么区别?