0

thank you for taking a look at my question.

This is a Java file when executed, takes in a name of a student and corresponding grades and when you type nothing in for the name, it computes the average of all of the students' grades. What I'm slightly confused about is why we need the below for the doWhile to continue asking for input?

// Read in the newline before looping back
                input.nextLine();

I realized if I comment out the above line, the doWhile runs once and does not take any input for newStudent and exits the loop but I feel like the line below should already take care of it within the doWhile?

newStudent = input.nextLine();

Below is the entire code snippet.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class HashMapGradebook {

    public static void main(String[] args) {

        HashMap<String, Double> students = new HashMap<>();
        Scanner input = new Scanner(System.in);
        String newStudent;

        System.out.println("Enter your students (or ENTER to finish):");

        // Get student names and grades
        do {

            System.out.print("Student: ");
            newStudent = input.nextLine();

            if (!newStudent.equals("")) {
                System.out.print("Grade: ");
                Double newGrade = input.nextDouble();
                students.put(newStudent, newGrade);

                // Read in the newline before looping back
                input.nextLine();
            }

        } while(!newStudent.equals(""));

        // Print class roster
        System.out.println("\nClass roster:");
        double sum = 0.0;

        for (Map.Entry<String, Double> student : students.entrySet()) {
            System.out.println(student.getKey() + " (" + student.getValue() + ")");
            sum += student.getValue();
        }

        double avg = sum / students.size();
        System.out.println("Average grade: " + avg);
    }
}
John Kang
  • 1
  • 1

0 Answers0