循环语句程序中的逻辑错误



我的程序中有一个逻辑错误。如果我输入数据,程序将正确编译;3名学生,詹姆斯100,瑞奇98,埃里克70。如果我输入James 100、Eric 70和Ricky 98,它显示James和Eric是顶尖学生,这是不正确的,任何帮助都将不胜感激。

    import java.util.Scanner;
public class FindHighestScores {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String studentName = "";
    String topStudentName = "";
    String top2ndStudentName = "";
    int grade = 0;
    int topStudentGrade = 0;
    int top2ndStudentGrade = 0;
    int studentNumber = 0;
    System.out.print("Enter the number of students: ");
    studentNumber = input.nextInt();
    System.out.print("Enter a student name: ");
    topStudentName = input.next();
    System.out.print("Enter a students score: ");
    topStudentGrade = input.nextInt();
    System.out.print("Enter a student name: ");
    top2ndStudentName = input.next();
    System.out.print("Enter a students score: ");
    top2ndStudentGrade = input.nextInt();
    int count = 2;
    while (count < studentNumber) {
        System.out.print("Enter a student name: ");
        studentName = input.next();
        System.out.print("Enter a students score: ");
        grade = input.nextInt();
        if (grade > topStudentGrade) {
            grade = topStudentGrade;
            studentName = topStudentName;
        }
        if (grade > top2ndStudentGrade) {
            grade = top2ndStudentGrade;
            studentName = top2ndStudentName;
        }
        count++;
    }
    System.out.println("Top two students:" );
    System.out.println(topStudentName + "'s score is " + topStudentGrade);
    System.out.println(top2ndStudentName + "'s score is " + top2ndStudentGrade);
    input.close();
    }
}

您的问题在这里:

 if (grade > topStudentGrade) {
        grade = topStudentGrade;
        studentName = topStudentName;
    }
    if (grade > top2ndStudentGrade) {
        grade = top2ndStudentGrade;
        studentName = top2ndStudentName;
    }

应该是:

 if (grade > topStudentGrade) {
        topStudentGrade = grade; // these are backwards
        topStudentName = studentName;
    }else if (grade > top2ndStudentGrade) {
        top2ndStudentGrade = grade; //backwards again
        top2ndStudentName = studentName;
    }

将第二个语句设为else if语句,否则会得到相同的结果。你看看它是否是第二高的,如果它不是最高的。

我也会改变你处理输入的方式。在你得到学生人数后,创建一个循环,得到每个学生的名字和分数。然后,您可以编写另一个函数,将学生数组传递到该函数中,该函数将检查最高分数。

此外,count应设置为0:count = 0;

你不需要这些,按照目前的设置方式:

//This is the first set of inputs at the beginning of your program.
    System.out.print("Enter the number of students: ");
studentNumber = input.nextInt();
System.out.print("Enter a student name: ");
topStudentName = input.next();
System.out.print("Enter a students score: ");
topStudentGrade = input.nextInt();
System.out.print("Enter a student name: ");
top2ndStudentName = input.next();
System.out.print("Enter a students score: ");
top2ndStudentGrade = input.nextInt();

最新更新