我正在创建一个java程序,它允许我计算我输入的平均投票数,当我最终输入负数时,程序停止。该程序工作正常,但有一部分程序未显示。
以下是该计划:
public static void main (String[] args) {
System.out.println("This program calculate the average of your votes");
Scanner keyboard = new Scanner(System.in);
String answer;
do {
int sum = 0, myVotes=0;
System.out.println("Enter your votes and at the end a negative number");
boolean average = true;
while(average ) {
int votes = keyboard.nextInt();
if (votes >0) {
sum = sum + votes;
myVotes++;
} else if (myVotes>0){
System.out.println("The average is :" + (sum/myVotes));
} else if (votes<0){
average = false;
}
}
System.out.println("Do you want to calculate another average : yes or no");
answer = keyboard.next();
}while(answer.equalsIgnoreCase("yes"));
}
这是程序未显示的部分:
您想计算另一个平均值:是或否; exc ..
谢谢大家的帮助。
答案 0 :(得分:2)
问题在于您的if-else
逻辑。移除if (myVotes>0)
并将System.out.println("The average is :" + (sum/myVotes));
行排除在while(average )
循环之外:
以下是更正后的代码段:
do {
int sum = 0, myVotes=0;
System.out.println("Enter your votes and at the end a negative number");
boolean average = true;
while(average ) {
int votes = keyboard.nextInt();
if (votes >0) {
sum = sum + votes;
myVotes++;
} else if (votes<0){
average = false;
}
}
if (myVotes != 0){//To handle divide by 0 exception
System.out.println("The average is :" + (sum/myVotes));
}
System.out.println("Do you want to calculate another average : yes or no");
answer = keyboard.next();
}while(answer.equalsIgnoreCase("yes"));