Do not write a class as specified regarding the array. Instead use two one-dimen
ID: 3761550 • Letter: D
Question
Do not write a class as specified regarding the array. Instead use two one-dimensional arrays of size 12 each (parallel arrays) and four methods to solve the problem as specified. One array will hold the names of the months and the other array will hold the rainfall in inches for the months. Pass the appropriate array or arrays to the methods as needed.
Write a RainFall class that stores the total rainfall for each of 12 months into an array of double s. The program should have methods that return the following:
• the total rainfall for the year
• the average monthly rainfall
• the month with the most rain
• the month with the least rain
Demonstrate the class in a complete program. Input Validation: Do not accept negative numbers for monthly rainfall figures.
Explanation / Answer
Complete Program:
import javax.swing.JOptionPane;
class Rainfall {
private double[] year;
public Rainfall(double[] y) {
year = new double[y.length];
for (int index = 0; index < y.length; index++)
year[index] = y[index];
}
public double getTotal() {
double total = 0;
for (int index = 0; index < year.length; index++) {
total += year[index];
}
return total;
}
public double getAverage() {
double average = getTotal() / 12;
return average;
}
public double getlargest() {
double largest = 0;
for (int index = 0; index < year.length; index++) {
if (year[index] > largest) {
largest = year[index];
}
}
return largest;
}
public double getsmallest() {
double smallest = year[0];
for (int index = 1; index < year.length; index++) {
if (year[index] < smallest)
smallest = year[index];
}
return smallest;
}
public static void main(String[] args) {
final int month = 12;
double[] year = new double[month];
setmonths(year);
Rainfall r = new Rainfall(year);
JOptionPane.showMessageDialog(
null,
"The Total Rain fall is" + r.getTotal()
+ " The Average Rainfall is" + r.getAverage()
+ " The Month with most rainfall is" + r.getlargest()
+ " The Month with the least rainfall is"
+ r.getsmallest());
System.exit(0);
}
private static void setmonths(double[] a)
{
String input = null;
for (int i = 0; i < a.length; i++)
{
input = JOptionPane.showInputDialog("Enter Month" +" "+ (i + 1)+" "+"Rainfall :");
a[i] = Double.parseDouble(input);
while(a[i]<0)
{
JOptionPane.showMessageDialog(null,"INVALID Rainfall");
input = JOptionPane.showInputDialog("Enter Month" +" "+ (i + 1)+" "+"Rainfall :");
a[i] = Double.parseDouble(input);
}
}
}
}
Sample output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.