Search code examples
javabluej

What is happening inside the for loop with grade and sum? I have no clue what it's doing


This is a program that calculates the users test average based on how many inputs he wants. But, I do not know what is happening inside the for loop and what it means. The grade and the sum.

   System.out.println("Welcome, please type your first name. ");
   String name = scan.nextLine();
   System.out.println("Welcome, please type your last name. ");
   String last = scan.nextLine();
   int numberOfTests;
   System.out.println("How many tests would you like the average of?");
   numberOfTests = scan.nextInt();

   while(numberOfTests<0)
   {
        System.out.println("Invalid input.");
        System.out.println("How many tests would you like the average 
        of?");
        numberOfTests = scan.nextInt();
   }
   double sum = 0;
   double grade;
   System.out.println("Enter " + numberOfTests + " scores.");
   for(int i = 0;i<numberOfTests;i++)
   {
    grade = scan.nextDouble();
    sum += grade;
   }
   double average = (sum/numberOfTests);
   System.out.println("Okay " + name.charAt(0) + last.charAt(0) + ", your 
   average score is " + (average));
   System.out.print("Your letter grade is ");

The program works.


Solution

  • It looks like scan is an instance of java.util.Scanner. This class is used to read from user input, so grade = scan.nextDouble() reads the next double from the user's input.

    Then sum += grade is equivalent to sum = sum + grade; it adds the grade that the user input to the total grade (sum).

    So the loop asks for numberOfTests inputs from the user, and adds them all together in sum.

    For details for how the input is read, look at the documentation for Scannner#nextDouble().