Home > Enterprise >  I cant get my nested loop to average student scores correctly after first loop
I cant get my nested loop to average student scores correctly after first loop

Time:04-20

This is my Java programming class assignment: Write a program, that takes users’ input and the number of students, and test scores. It should then average test scores and display them on the screen. (Wants us to do this using a nested loop).

The issue that I am having is when the program goes into the second loop the sum is still totaling the scores from the previous loop. so it is throwing off any student average calculated after the first one.

'Import java.util.Scanner;'

class Main { public static void main(String[] args) {

int ans, ans1;
double sum = 0;

Scanner sc = new Scanner(System.in);

System.out.print("\n\nFor how many students do you have scores ? ");
ans = sc.nextInt(); //Number of Students

for (int x=1; x<=ans; x  ) {
System.out.print("\n\nHow many test scores does student #"   x " have? ");
  ans1 = sc.nextInt(); //Number of scores entered
  
  for (int z=1; z<=ans1; z  ) {
    double ans2;
    System.out.print("\nEnter score " z " for student "  x ": ");
    ans2 = sc.nextDouble();
    sum  = ans2   0; //Student Scores
  }

  double avg = sum/ans1;
  System.out.printf("\nStudent #" x " Average Score: %.1f", avg);

}

}

}

Output:

For how many students do you have scores ? 2

How many test scores does student #1 have? 3

Enter score 1 for student 1: 84

Enter score 2 for student 1: 79

Enter score 3 for student 1: 97

Student #1 Average Score: 86.7

How many test scores does student #2 have? 3

Enter score 1 for student 2: 92

Enter score 2 for student 2: 88

Enter score 3 for student 2: 94

Student #2 Average Score: 178.0 //Average should be 91.3

CodePudding user response:

You should reset the sum variable inside the loop.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        int ans, ans1;
        double sum = 0;
        
        Scanner key = new Scanner(System.in);
        
        System.out.println("\nHow many students have scores?: ");
        ans = key.nextInt();
        
        for(int i = 0; i < ans; i  ){
            System.out.print("\nHow many test scores does Student "  (i 1)   " have?: ");
            ans1 = key.nextInt();
            
            for(int j = 0; j < ans1; j  ){
                double ans2;
                System.out.print("\nEnter score "   (j   1)   " for Student "   (i   1)  ": ");
                ans2 = key.nextDouble();
                sum  = ans2;
            }
            double avg = sum/ans1;
            System.out.printf("\nStudent "   (i   1)   " Average score: %.1f", avg);
            sum = 0; //add this line
        }
    }
}

CodePudding user response:

The "sum" variable should be inside the ans loop as it must be reset for each student. :)

  •  Tags:  
  • java
  • Related