It has been quite a while since I have posted any code in Java. As I was going through some Java questioners, I came across the Rainfall problem. The rainfall problem in java is quite simple, the user is going to enter data, the average participation per day r something, and the output is some statistical information. To keep things interesting, no arrays can be used, so everything needs to be computed on the fly. For our purpose, the user will enter the last 12 months data, an he output will be the minimum, maximum and average participation. This is fairly simple and a great exam or interview question.

Note that the code will check that enteries are non negative numbers.

Here is how this is going to look in Java:

```import java.util.Scanner;

public class Rainfall {

public static void main(String[] args) {

//variable setup
Scanner input = new Scanner(System.in);
String userInput = "";
double sum = 0.0;
final int COUNT = 12;
boolean valid = true;

//initiazlize variables min and max to something out of range
double min = 999999999999.9;
double max = -0.1;
int min_month = 0;
int max_month = 0;

//temp variable
double curr = 0.0;

for (int i=0; i < COUNT; i++){

//user input validation
do{

//get user input
System.out.print("enter the rainfall for month number " + (i+1) +": ");
userInput=input.nextLine();

try{

//convert input to double
curr = Double.parseDouble(userInput);
valid = true;

//throw error if input is less than 0
if(curr < 0) throw new Exception();

} catch (Exception e) {

System.err.println("\nThat was not a valid entry! \nPlease try again.\n");
valid = false;
}
} while (!valid);

//keep a running total
sum+= curr;

//find min
if(curr < min){
min = curr;
min_month = i+1;
}

//find max
if(curr > max){
max = curr;
max_month = i+1;
}

} //end for loop

//compute the average
double avg = sum/COUNT;

//report the result
System.out.println("\nThe avg rainfall is " + String.format("%.2f", avg) +
"\n" + "The min rainfall is " + min + " for month number " + min_month +
"\n" + "The max rainfall is " + max + " for month number " + max_month );
}
}
```

Here is how the output should look like:

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.