显示哪个月的降雨量最低 - 数组java

时间:2016-10-06 15:42:06

标签: java arrays loops for-loop

    double rainfall[] =new double[6];
String months[]={"January", "February", "March", "April", "May", "June"};
double total =0;


for(int i=0;i<rainfall.length;i++){
    rainfall[i] = Double.parseDouble(JOptionPane.showInputDialog("Please enter rainfall for month " + (i +1)));
    total += rainfall[i];
}

System.out.println("The 6 mmonthly rainfalls are: ");

for(int i=0;i<rainfall.length;i++){
    System.out.println(months[i]+ " : "+ "\t" + rainfall[i]);    

}
double average = total/(double)rainfall.length;
System.out.println("Average rainfall: "+average);

double min = rainfall[0];
for(int i=1;i>rainfall.length;i++){
    if(rainfall[i]>min)
        min =rainfall[i];

}
    System.out.println("had the lowest rainfall: "+min);

所以这是我的代码,示例输出:

  1. 6个月的降雨量为:
  2. 1月:1.0
  3. 二月:2.0
  4. March:3.0
  5. 四月:4.0
  6. May:5.0
  7. 六月:6.0
  8. 平均降雨量:3.5
  9. 降雨量最低:1.0
  10. 正如你可以在示例输出的'9'中看到的那样,我有“降雨量最少”之前我必须把降雨量降到最低的月份。我不知道如何连接它们。对不起,如果这有点混乱,英语不是我的主要语言。提前谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您可以通过获取最小降雨量指数找到最小降雨量月份,并将降雨量按顺序映射到您可以获得最低降雨量月份的月份,如下所示...

您的代码

double min = rainfall[0];
for(int i=1;i>rainfall.length;i++){
    if(rainfall[i]>min)
        min =rainfall[i];

}

将其更改为

       int index = 0;
           int min = rainfall[index];
           for (int i=1; i<rainfall.length; i++){

               if (rainfall[i] < min ){
                   min = rainfall[i];
                   index = i;
               }


       }
    System.out.println("Lowest rainfall month is :" month[index]);
System.out.println("had the lowest rainfall: "+min);