Patryk Michta Patryk Michta - 1 month ago 10
Java Question

Showing which month had the lowest rainfall amount- arrays java

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


So this is the code I have, example output:


  1. The 6 mmonthly rainfalls are:

  2. January : 1.0

  3. February : 2.0

  4. March: 3.0

  5. April : 4.0

  6. May : 5.0

  7. June : 6.0

  8. Average rainfall: 3.5

  9. had the lowest rainfall: 1.0



As you can see in line '9' of example output I have "had the lowest rainfall" before had I have to put the month that had the lowest rainfall. I don't know how to connect them. Sorry if this is kind of chaotic, english is not my primary language. Thank you for help in advance.

Answer

You can find the minimum rainfall month by getting the index of minimum rainfall amount and as the rainfall amount is sequentially mapped to the months you can get the lowest rainfall month as below...

Your code

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

}

change it to

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