简体   繁体   中英

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. 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. Remove if (myVotes>0) and put System.out.println("The average is :" + (sum/myVotes)); line out of while(average ) loop:

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

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.

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