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.开发者_如何转开发
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
- Do
- Instead of checking for the last iteration to do something, refactor and take it outside of the loop
Related questions
- What is exactly the off-by-one errors in the while loop?
See also
- Wikipedia/Off-by-one error
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
- Java Language Guide/Autoboxing
- JLS 5.1.7 Boxing Conversion and 5.1.8 Unboxing Conversion
- Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives
Related questions
- What is the difference between an
int
and anInteger
in Java/C#? - Java: What’s the difference between autoboxing and casting?
- Why does
int num = Integer.getInteger(“123”)
throwNullPointerException
? - Why does autoboxing in Java allow me to have 3 possible values for a
boolean
? - Is it guaranteed that
new Integer(i) == i
in Java? (YES!!!) - When comparing two Integers in Java does auto-unboxing occur? (NO!!!)
- Java noob: generics over objects only? (yes, unfortunately)
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
- Why does
(360 / 24) / 60 = 0
in Java- Because it performs integer division. This is why the cast to
(double)
prior to the division in above code is necessary, so that it performs floating point division.
- Because it performs integer division. This is why the cast to
- How does the ternary operator work?
- This is the
?:
operator in above code, also known as the conditional operator. - See also: JLS 15.25 Conditional Operator ?:
- This is the
Change your end condition to be strictly less than 4 and put the code that prints out the total and average outside the loop.
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 ()
}
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
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
精彩评论