簡體   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