tags:

views:

136

answers:

4
+1  Q: 

for loop structure

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.

+3  A: 

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
A: 

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
This is cleaner but the results are the same?
jjason89
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
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
How do you re-enter code so it show up correctly?I spaced over 5 spaces.???
jjason89
This code as is doesn't add the last `inputNumber` to the `sum`.
polygenelubricants
+11  A: 

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

polygenelubricants
A: 

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