I'm writing a program that calculates and displays the average bowling scores of each bowler the user inputs. I'm having trouble calculating the average of the 3 scores, right now I think it's calculating the total of the the scores. How do I make it so it calculates the average of the scores
public static void main (String [] args)
{
//local constants
//local variables
String bowler = "";
int total = 0;
int average = 0;
int score1 = 0;
int score2 = 0;
int score3 = 0;
/******************** Start main method *****************/
//Enter in the name of the first bowler
System.out.print(setLeft(40," Input First Bowler or stop to Quit: "));
bowler = Keyboard.readString();
//Enter While loop if input isn't q
while(!bowler.equals("stop"))
{
System.out.print(setLeft(40," 1st Bowling Score:"));
score1 = Keyboard.readInt();
System.out.print(setLeft(40," 2nd Bowling Score:"));
score2 = Keyboard.readInt();
System.out.print(setLeft(40," 3rd Bowling Score:"));
score3 = Keyboard.readInt();
if(score1 >= 0 && score1 <= 300 && score2 >= 0 && score2 <= 300 && score3 >= 0 && score3 <= 300)
{
total += score1;
total += score2;
total += score3;
System.out.println(setLeft(41,"Total: ")+ total);
average = score1 + score2 + score3 / 3;
System.out.println(setLeft(41,"Average: ") + average);
}
else
{
System.out.println(setLeft(40,"Error"));
}
Java's mathematical operators obey the standard mathematical precedence, so it's
int average = score1 + score2 + (score3 / 3);
However, your intention was likely
int average = (score1 + score2 + score3) / 3;
Finally you most likely want to do this calculation in double
(or float
) arithmetic, otherwise it will be rounded down
double average = (double)(score1 + score2 + score3) / 3;
The division ( /
) operator has a higher precedence than the addition operator ( +
), so you need to enclose the sum with brackets before dividing:
average = (score1 + score2 + score3) / 3;
// Here --^------------------------^
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.