jjason89
jjason89

Reputation: 39

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.

Upvotes: 1

Views: 1328

Answers (5)

Alex
Alex

Reputation: 17

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

Upvotes: 0

YoK
YoK

Reputation: 14505

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

Upvotes: 0

polygenelubricants
polygenelubricants

Reputation: 383746

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

Upvotes: 12

Burbas
Burbas

Reputation: 803

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 ()
}

Upvotes: 0

ChrisF
ChrisF

Reputation: 137148

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

Upvotes: 3

Related Questions