Tekt Tekt - 29 days ago 8
Java Question

Java - Using for loop to average set of grades read in from keyboard

First time poster here. I'm aware of the negative stigma carried with asking for help on homework assignments, however I believe this would be an exception as this is an intro course and the professor stated specifically to use Google to find examples of for loops in Java (of which we have yet to even cover in class). I have absolutely no Java experience and would really appreciate any feedback:

Program asks user how many grades there are.

Program asks user for each grade (for loop needed and should sum grades within loop).

Take sum of all grades, compute average and store in a float variable grade.

Print grade value to console and append a number to a string such as

"Grade Average is: " + grade


Example should read as:

Enter number of grades: 2
Enter grade: 90
Enter grade: 81
Grade Average is: 85.5


My code so far (not much here):

// This program computes the letter grades for number of grades given by user

import java.util.*;

public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);
}
}


Edit:

// This program computes the letter grades for number of grades given by user

import java.util.*;

public class GradeAverage
{
public static void main(String[] args)
{
int count;
float sum = 0;
float grade;
Scanner scan = new Scanner(System.in);

System.out.print("Enter number of grades: ");
count = scan.nextInt();

for (int i = 0; i < count; ++i)
System.out.print("Enter grade " + (i + 1) + ": ");
grade = scan.nextFloat();
sum += grade;

System.out.println("The average of the grades is: " + sum/count);
}
}


This is what I have now, however a test displays incorrect results (example):

Enter number of grades: 2
Enter grade 1: Enter grade 2: 50 50
The average of the grades is: 25.0


Each grade needs to be entered on separate lines so the averaging is skewed as a result.

Answer
import java.util.Scanner;     
public static void main(String[] args) {
            int count = 0;
            float sum = 0;
            float grade = 0;
            Scanner scan = new Scanner(System.in);

            System.out.print("Enter number of grades: ");
            count = scan.nextInt();

            for (int i = 0; i < count; i++) {
                System.out.print("Enter grade no " + (i + 1) + " : ");
                grade = scan.nextFloat();
                sum += grade;
            }
            System.out.println("Sum = " + sum);
            System.out.println("Average = " + sum / (float) count);
        }