简体   繁体   English

java程序:计算平均值?

[英]java program : calculate the average?

I'm creating a java program, which allows me to calculate the average number of votes entered by me, and when I finally enter a negative number the program stops. 我正在创建一个Java程序,该程序可以让我计算出我输入的平均票数,而当我最终输入负数时,该程序将停止。 The program works fine but there is a section of the program that is not shown. 该程序运行正常,但该程序的一部分未显示。

Here is the program : 这是程序:

 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"));
}

This is the section which is not show by the program : 这是程序未显示的部分:

Do you want to calculate another average : yes or no; 您是否要计算另一个平均值:是或否; exc .. 排除..

Thank you all for the helping. 谢谢大家的帮助。

Problem is in your if-else logic. 问题出在您的if-else逻辑中。 Remove if (myVotes>0) and put System.out.println("The average is :" + (sum/myVotes)); 删除if (myVotes>0)并放入System.out.println("The average is :" + (sum/myVotes)); line out of while(average ) loop: while(average )循环中排成一行:

Following is corrected code snippet: 以下是更正的代码段:

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