给了我降雨问题,要计算三个月的总降雨量,然后确定平均值,但是由于某种原因,循环不会在三个条目处结束。我已经定义了计数器,甚至使用了“ break”,但是由于某种原因,编译器只是允许用户继续输入。如果循环没有结束,我将无法计算平均降雨量

我已经定义了循环并创建了while语句

import java.util.Scanner;

public class rainfall {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    double average;
    double total = 0;
    final double rainfall[] = new double[3];

    for (int counter = 0; counter <= rainfall.length; counter++) {
      do {
        System.out.print("Enter amount of rainfall:");
        rainfall[counter] = input.nextInt();
      } // end of do statement

      while (rainfall[counter] <= 3);
    } // end of for statement

    for (int counter = 0; counter <= rainfall.length; counter++) {
      System.out.println(counter + "t\t" + rainfall[counter]);
      //          display rainfall in the array

      total = total + rainfall[counter]; //calculate total rainfall

      System.out.println("Total rainfall is:" + total);
      average = total / 3; //calculate average rainfall
      System.out.print("Average rainfall is" + average);
    }
  }
}


我希望用户只能输入三个月的结果,然后再给出平均值,但是循环不会停止,因此无法得出平均值。

最佳答案

那是可行的版本:

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);

  double average;
  double total = 0;
  final double rainfall[] = new double[3];

  for (int counter = 0; counter < rainfall.length; counter++) {
        System.out.print("Enter amount of rainfall:");
        rainfall[counter] = input.nextInt();
  } // end of for statement

  for (int counter = 0; counter < rainfall.length; counter++) {
    System.out.println(counter + "t\t" + rainfall[counter]);
    //          display rainfall in the array

    total = total + rainfall[counter]; //calculate total rainfall

    System.out.println("Total rainfall is:" + total);
    average = total / 3; //calculate average rainfall
    System.out.print("Average rainfall is" + average);
 }
}


while循环是不必要的,并且
08-06 17:50