1

This program will calculate the average grade for 4 exams using a for loop by prompting the user for exam grades, one at a time, then calculate the average and display the result.

public class ExamsFor4 {

public static void main(String[] arguments) {


int inputNumber; // One of the exams input by the user.
int sum = 0;     // The sum of the exams.
int i;       // Number of exams.
Double Avg;      // The average of the exams.

TextIO.put("Please enter the first exam: ");        // get the first exam.
inputNumber = TextIO.getlnInt();    

for ( i = 1; i <= 4; i++ ) {  

    sum += inputNumber;                 // Add inputNumber to running sum.
    TextIO.put("Please enter the next exam: ");     // get the next exam.   
    inputNumber = TextIO.getlnInt();

        if (i == 4) {
            Avg = ((double)sum) / i;
            TextIO.putln();
            TextIO.putln("The total sum for all " + i +" exams is " + sum);
            TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
            break;

        }
} 

}   // end main ()
}  // end class ExamsFor4

My result:

Please enter the first exam: 100
Please enter the next exam: 99
Please enter the next exam: 98
Please enter the next exam: 97
Please enter the next exam: 96
The total sum for all 4 exams is 394
The average for the exams entered is 98.50.

This would be correct except for the last print out of: 'Please enter the next exam: 96' I tried putting the IF statement between the 'sum' line and the TextIO.put 'Enter next exam', but that isolates it.

Thanks, from a Network Dude trap in a Programmer's world.

Donal Fellows
  • 120,022
  • 18
  • 134
  • 199
jjason89
  • 39
  • 1
  • 2
  • 6
  • 9
    this is the type of thing you're supposed to struggle through and either figure out on your own or fail. I'm glad I didn't have stack overflow as a resource when I was in school. – jim Jul 11 '10 at 16:03

5 Answers5

12

You have what is called an off-by-one error, compounded by the fact that you're convoluting your loop logic unnecessarily.

With regards to the loop, I recommend two things:

  • Don't loop for (int i = 1; i <= N; i++); it's atypical
    • Do for (int i = 0; i < N; i++); it's more typical
  • Instead of checking for the last iteration to do something, refactor and take it outside of the loop

Related questions

See also


On Double Avg

In Java, variable names start with lowercase. Moreover, Double is a reference type, the box for the primitive double. Whenever possible, you should prefer double to Double

See also

Related questions


Rewrite

Here's a way to rewrite the code that makes it more readable. I used java.util.Scanner since I don't think TextIO is standard, but the essence remains the same.

import java.util.*;

public class ExamsFor4 {
    public static void main(String[] arguments) {
        Scanner sc = new Scanner(System.in);
        final int NUM_EXAMS = 4;
        int sum = 0;

        for (int i = 0; i < NUM_EXAMS; i++) {
            System.out.printf("Please enter the %s exam: ",
                (i == 0) ? "first" : "next"
            );
            sum += sc.nextInt();
        }
        System.out.printf("Total is %d%n", sum);
        System.out.printf("Average is %1.2f%n", ((double) sum) / NUM_EXAMS);
    }
}

An example session is as follows:

Please enter the first exam: 4
Please enter the next exam: 5
Please enter the next exam: 7
Please enter the next exam: 9
Total is 25
Average is 6.25

Note that:

  • Only necessary variables are declared
    • The loop index is local only to the loop
  • There are no cluttering comments
    • Instead, focus on writing clear, concise, readable code
  • If it makes sense to make something final, do so
    • Constants in Java is all uppercase

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 348,637
  • 121
  • 546
  • 611
3

Change your end condition to be strictly less than 4 and put the code that prints out the total and average outside the loop.

ChrisF
  • 127,439
  • 29
  • 243
  • 315
0
import java.util.Scanner;
public class ExamsFor4 {

public static void main(String[] arguments) {

    int sum = 0; // The sum of the exams.
    int i = 1; // Number of exams.
    double avg = 0; // The average of the exams.

    Scanner in = new Scanner(System.in);
    System.out.print("Please enter the first exam: ");
    sum += in.nextInt();
    i++;
    while(i<=4){
        System.out.print("Please enter the next exam: ");
        sum += in.nextInt();
        if(i==4)
            break;// this line is so that it wont increment an extra time.
        i++;
    }
    System.out.println("The total sum for all " + i +" exams is " + sum);
    avg = ((double)sum/i);
    System.out.println("The average for the exams entered is" + avg);
} // end main ()
} // end class ExamsFor4
DaveShaw
  • 48,792
  • 16
  • 106
  • 133
Alex
  • 21
  • 2
0

You should probably put the if-statment outside the for-loop. That way you don't need the if-statement. Second the statement in the loop should be < 4 instead of <= 4.

public class ExamsFor4 {

public static void main(String[] arguments) {


int inputNumber; // One of the exams input by the user.
int sum = 0;     // The sum of the exams.
int i;       // Number of exams.
Double Avg;      // The average of the exams.

TextIO.put("Please enter the first exam: ");        // get the first exam.
inputNumber = TextIO.getlnInt();    

for ( i = 1; i < 4; i++ ) {  

    sum += inputNumber;                 // Add inputNumber to running sum.
    TextIO.put("Please enter the next exam: ");     // get the next exam.   
    inputNumber = TextIO.getlnInt();
} 

Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;

}   // end main ()
}
Burbas
  • 773
  • 6
  • 20
  • This is cleaner but the results are the same? – jjason89 Jul 11 '10 at 16:40
  • 1
    No I was wrong. It now appears to stop correctly after 4 entries, but the last entry doesn't get added to the sum. Still fighting the one-off error. – jjason89 Jul 11 '10 at 16:43
  • I had to remove the lines asking for input before the loop. for (i = 0; i < 4; i++ ) { TextIO.put("Please enter an exam: "); // get the next exam. inputNumber = TextIO.getlnInt(); sum += inputNumber; // Add inputNumber to running sum. } Thanks to all for helping me work through this. – jjason89 Jul 12 '10 at 01:24
  • This code as is doesn't add the last `inputNumber` to the `sum`. – polygenelubricants Jul 13 '10 at 09:14
0

Just making few changes in your code makes it work. But you should follow cleaner approach as proposed in some of answers.

public class ExamsFor4 {

  public static void main(String[] arguments) {
    int inputNumber; // One of the exams input by the user.
    int sum = 0;     // The sum of the exams.
    int i;       // Number of exams.
    double Avg;      // The average of the exams.

    TextIO.put("Please enter the first exam: ");        // get the first exam.
    inputNumber = TextIO.getlnInt();    
    sum += inputNumber;

    for ( i = 1; i < 4; i++ ) {  

      TextIO.put("Please enter the next exam: ");     // get the next exam.   
      inputNumber = TextIO.getlnInt();
      sum += inputNumber;                 // Add inputNumber to running sum.

    } 

    Avg = ((double)sum) / i;
    TextIO.putln();
    TextIO.putln("The total sum for all " + i +" exams is " + sum);
    TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);

  }   // end main ()
}  // end class ExamsFor4
YoK
  • 13,731
  • 4
  • 46
  • 66