In JAVA: How do I create an array based on user input? Specfically I need to cre
ID: 3811460 • Letter: I
Question
In JAVA: How do I create an array based on user input? Specfically I need to create an array that stores the amount of rainfall for each month of the year. The program will ask the user for the rainfall for each month and store the data in the array.
Inside the main() method, first you will get the rainfall data for each of the 12 months in 2016 from the user and stores them in a double array. Next, you will need to design the following four value-returning methods that compute and return to main() the totalRainfall, averageRainfall, driestMonth, and wettestMonth. The last two methods return the index (or number) of the month with the lowest and highest rainfall amounts, not the amount of rain that fell those months. Notice that this month index (or number) can be used to obtain the amount of rain that fell those months.
Explanation / Answer
Code :-
Note:- month index is starting from 0 (Jan) - 11 (dec)
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Rain
{
public double totalRain(double[] arr){
double tot=0;
for(int i=0;i<arr.length;i++){
tot=tot+arr[i];
}
return tot;
}
public double avgRain(double[] arr){
double tot=0;
for(int i=0;i<arr.length;i++){
tot=tot+arr[i];
}
return tot/12.0;
}
public int driest_Month(double[] arr){
double min=0;
int min_index=0;
for(int i=0;i<arr.length;i++){
if(i==0){
min=arr[i];
min_index=i;
}
else if(arr[i]<min){
min=arr[i];
min_index=i;
}
}
return min_index;
}
public int wettest_Month(double[] arr){
double max=0;
int max_index=0;
for(int i=0;i<arr.length;i++){
if(i==0){
max=arr[i];
max_index=i;
}
else if(arr[i]>max){
max=arr[i];
max_index=i;
}
}
return max_index;
}
public static void main (String[] args) throws java.lang.Exception
{
Rain obj1=new Rain();
double[] rain_month=new double[12];
Scanner reader = new Scanner(System.in); // Reading from System.in
for(int i=0;i<rain_month.length;i++){
System.out.println("Enter a amount of rainfall in month number "+i+":");
rain_month[i] = reader.nextInt(); // Scans the next token of the input as an int.
}
System.out.println("The total rainfall in 12 months = "+obj1.totalRain(rain_month));
System.out.println("The average rainfall in 12 months = "+obj1.avgRain(rain_month));
System.out.println("The month index with highest rainfall = "+obj1.wettest_Month(rain_month));
System.out.println("The month index with lowest rainfall = "+obj1.driest_Month(rain_month));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.