2017-12-06 12 views
-1

私は私が入力した平均投票数を計算できるJavaプログラムを作成しています。最後に負の数を入力するとプログラムが停止します。プログラムは正常に動作しますが、表示されていないプログラムのセクションがあります。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")); 
} 

:ここ

はプログラムでyesまたはno。
exc。

ありがとうございました。

+0

プログラムが正常に動作し、唯一の問題は、私は別の平均値を計算することができないということです。 –

+0

@Fubar String answer = "yes"、これは問題ではありません –

+0

'else if(votes <0){'を打つことは決してありません。したがって、内部whileループは決して終了しません。 – notyou

答えて

2

問題はif-elseロジックにあります。 if (myVotes>0)を外し、while(average)ループの外にSystem.out.println("The average is :" + (sum/myVotes));行を置く:

次は、修正されたコードスニペットです:

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

良い!ありがとうございました! –

+0

数分で正解にすることを検討してください。 –