Golf score program?
So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
开发者_Go百科}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
- Don't always divide by 10 - use the value of
counter
. - Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.
精彩评论