0

I am trying to write a code to ask for student names and scores, and print the top two. Unfortunately, in my for loop I can't get it to take input for the name or score. It just continuously submits without progressing.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    System.out.println("Enter the number of students: ");
    int stuNum = in.nextInt();

    String bestStudent = "";
    String nextStudent = "";
    String studentName = "";

    double bestScore = 0;
    double nextScore = 0;
    double studentScore = 0;

    for (int count = 0; count < (stuNum - 1); count++) {
        System.out.println("Enter a student name: ");
        studentName = in.nextLine();

        System.out.println("Enter a student score: ");
        studentScore = in.nextDouble();

        if (studentScore > bestScore) {
            bestScore = studentScore;
            bestStudent = studentName;
        }
        else if (studentScore < bestScore && studentScore > nextScore) {
            nextScore = studentScore;
            nextStudent = studentName;
        }
    }

    System.out.println("The top two students are:");
    System.out.println(bestStudent + ", with a score of: " + bestScore + ".");
    System.out.println(nextStudent + ", with a score of: " + nextScore + ".");

}
  • 1
    call `in.nextLine();` right after your call to `in.nextDouble()` – RAZ_Muh_Taz Oct 19 '18 at 22:14
  • It worked when I put in.nextLine(); after the first in.nextLine(); – Skuldakn Oct 19 '18 at 22:32
  • it seems like it but it actually is correct to place it after the in.nextDouble(); the only reason it works is because of the for loop. what happens when you run the loop once? what happens when you reach the last student? Does it still work? – RAZ_Muh_Taz Oct 19 '18 at 22:43

0 Answers0