繁体   English   中英

java程序:计算平均值?

[英]java program : calculate the average?

我正在创建一个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"));
}

这是程序未显示的部分:

您是否要计算另一个平均值:是或否; 排除..

谢谢大家的帮助。

问题出在您的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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM