[英]how would i implement -1 when running the code
代码工作正常,但我似乎无法使用-1作为我用来计算平均值的唯一输入来运行代码。
import java.util.*;
class Bowling {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int G = 0;
int scores = 0;
double avg = 0;
double highest_average = 0;
int times = 0;
int players = 4;
for (int i = 1; i <= players; i++) {
System.out.println("Player " + i);
if (avg > highest_average)
highest_average = avg;
do {
System.out.println("Enter your bowling score:");
G = keyboard.nextInt();
scores += G;
times++;
}
while ((G != -1));
scores += +1;
times = times - 1;
avg = (scores) / (times);
System.out.printf("Average= %.2f\n", avg);
scores = 0;
times = 0;
System.out.println("");
}
System.out.println("Highest average:" + highest_average);
}
}
这是一个示例运行:因此,代码工作正常,但是我不知道是否应该使用IF语句让-1计算为平均值。
Player 1
Enter your bowling score:
300
Enter your bowling score:
222
Enter your bowling score:
-1
Average= 261.00
Player 2
Enter your bowling score:
210
Enter your bowling score:
211
Enter your bowling score:
300
Enter your bowling score:
-1
Average= 240.00
Player 3
Enter your bowling score:
233
Enter your bowling score:
-1
Average= 233.00
Player 4
Enter your bowling score:
112
Enter your bowling score:
-1
Average= 112.00
Highest average:261.00
这是另一次运行,但首先输入-1
Player 1
Enter your bowling score:
-1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at LabQuiz1.main(LabQuiz1.java:33) // I keep getting this when -1 is inputted I have been thinking of using a IF statement to tell the code that if -1 is implemented it should still calculate 0 as the average.
您的代码在这里:
scores += + 1;//change to scores+=1
times = times - 1; //in do while loop you increment by one and now you decrement it and hence 0
avg = (scores)/(times);//you could check for times if 0 here. and you are dividing by integer if you want accurate decimal result change denominator to decimal as well.
更改为:
scores += 1;
times = times - 1;
avg = times == 0? 0: (scores/(times * 1.));
如果使用-1作为特殊数字退出处理,则应使用if条件不将输入作为计算的一部分进行处理。
double highest_average=0;
int players = 4;
for(int i =1; i<=players; i++) {
double avg = 0;
int times = 0;
int scores = 0;
System.out.println("Player " + i);
if (avg > highest_average)
highest_average= avg;
do
{
System.out.println("Enter your bowling score:");
G = keyboard.nextInt();
if(G ==-1)
break;
scores += G;
times++;
}
while(true);
// remove the following lines that aren't necessary anymore
//scores += + 1;
//times = times - 1;
if(times > 0)
avg = (scores)/(times);
System.out.printf("Average= %.2f\n", avg);
//scores =0; times =0;
System.out.println("");
}
如果您不想允许负数, 请相应地更改if条件。
您可以将do / while条件修改为do ... while(true),因为现在退出break语句上的循环。
您可以将avg , scores和times变量移动到for循环内,因为它们仅在for循环的范围内使用。 这些变量将初始化为0,而不需要在底部再次初始化值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.