我的程序中有一个逻辑错误。如果我输入数据,程序会正确编译; 3名学生,詹姆斯100,瑞奇98,埃里克70.如果我进入詹姆斯100,埃里克70和瑞奇98,它显示詹姆斯和埃里克作为顶级学生,这是不正确的任何帮助将不胜感激。
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();
}
}
答案 0 :(得分:0)
你的问题在这里:
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();