我没有得到正确的结果,不确定我错过了什么(逻辑不正确,缺少步骤?)

时间:2013-01-29 20:42:56

标签: java

我试图让这个问题正常工作,它要求输入一些分数,然后它应该显示得分最高的人的名字。我输入的最后一个分数是最高分,问题是输入的最后一个分数不一定是输入的最高分。关于如何解决这个问题的任何想法将不胜感激。这是家庭作业,所以没有人说“使用列表或数组”,我们没有在课堂上讨论过,因此不应该用它来解决这个问题。

       public static void main(String[] args) 
       {
            // variables
            Scanner input = new Scanner(System.in);
            int count = 0;
            int numStudents;
            double grade = 0, highestGrade = 0;
            String name = "", highName = "";

            String numGrades =
                    JOptionPane.showInputDialog
                    ("How many student grades are you entering: ");
            numStudents = Integer.parseInt(numGrades);

            //for(int count = 0; count < numStudents; count++)
            while(count < numStudents)
            {
            // prompt for the user to enter grades
            String inputName =
                    JOptionPane.showInputDialog("Enter a student name: ");
            name = inputName;
            //name = input.next(inputName);

            String inputGrade = 
                   JOptionPane.showInputDialog("What is that students grade: ");
            grade = Double.parseDouble(inputGrade);
            //grade = input.nextDouble();

            count++; 
            //if(grade < highestGrade)
            if(highestGrade > grade)
            {
                name = highName;
                grade = highestGrade;
            }
            else 
            {
                continue;
            }        
            }
            JOptionPane.showMessageDialog
                    (null, "The student with the highest score is " + name + 
                    " with a grade of " + grade);           
        }

2 个答案:

答案 0 :(得分:3)

 if(highestGrade > grade)
            {
                name = highName;
                grade = highestGrade;
            }

由于您希望找到最高等级和名称,因此上述内容应相反。

 if(grade > highestGrade )
            {
                highName = name;
                highestGrade = grade;
            }

此外,打印找到的值:

     JOptionPane.showMessageDialog
                 (null, "The student with the highest score is " + highName +  
                  " with a grade of " + highestGrade);        

答案 1 :(得分:2)

这是倒退:

if(highestGrade > grade)

应该是

if(highestGrade < grade)

或更可理解:

if(grade > highestGrade)

编辑:这也是倒退......

name = highName;
grade = highestGrade;