Write a program were you use an array to store the numbers from each line and us
ID: 653527 • Letter: W
Question
Write a program were you use an array to store the numbers from each line and use methods to do the calculations.
In the main method, after you have read the first number (an integerr giving a count of the rest of the nubers in the line), create an array object. Then, read the numbers in the line and store in this array object.
Delcare methods named max, min, and sum as follows:
private static double max(double[] array){ // write your code for doing the calculations here.
}
private static double min(double[] array){ // write your code for doing the calculations here.
}
private static double sum(double[] array){ // write your code for doing the calculations here.
}
In the main method follow this idea,
LOOP OVER LINES
READ DOUBLES IN THE LINE INTO AN ARRAY
max = CALL MAX
min = CALL MIN
sum = CALL SUM
average = sum/count
PRINT stuff
END LOOP
Sample Input: 5 1.0 2.0 3.0 4.0 5.0
11 51.94 96.63 27.05 48.42 95.97 81.35 59.3 28.01 44.29 35.9 68.56
1 55.22
Sample Output: 15.00 3.00 1.00 5.00
637.42 57.95 27.05 96.63
55.22 55.22 55.22 55.22
Explanation / Answer
Required Solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Calculations
{
public static void main(String[] args) throws FileNotFoundException
{
File file=new File("Input.txt");
if(!file.exists())
{
System.out.println("Invalid file path");
return;
}
Scanner scanner=new Scanner(file);
while(scanner.hasNextLine()){
//read count of numbers
String line=scanner.nextLine();
int numLine=Integer.parseInt(line.split(" ")[0]);
int j=0;
//declaration of array
double[] arr=new double[numLine];
//iterate and read numbers
while(j<numLine)
{
arr[j]=Double.parseDouble(line.split(" ")[j+1]);
j++;
}
//print result
System.out.println(max(arr)+" "+min(arr)+" "+sum(arr)+" "+sum(arr)/numLine);
}
scanner.close();
}//end of main method
private static double max(double[] array)
{
double max=array[0];
for(int i=1;i<array.length;i++)
{
if(max<array[i])
max=array[i];
}
return max;
}//end of max method
private static double min(double[] array)
{
double min=array[0];
for(int i=1;i<array.length;i++)
{
if(min>array[i])
min=array[i];
}
return min;
}//end of min method
private static double sum(double[] array)
{
double sum=0;
for(int i=0;i<array.length;i++)
{
sum+=array[i];
}
return sum;
}//end of sum method
}//end of class
Input file:Input.txt
5 1.0 2.0 3.0 4.0 5.0
11 51.94 96.63 27.05 48.42 95.97 81.35 59.3 28.01 44.29 35.9 68.56
1 55.22
Sample Output:
5.0 1.0 15.0 3.0
96.63 27.05 637.420 57.9473
55.22 55.22 55.22 55.22
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.