Write a class name ArrayOperations with the following static methods: -getTotal
ID: 3683823 • Letter: W
Question
Write a class name ArrayOperations with the following static methods:
-getTotal = this method should accept a 1D array as its argument and return the total of the values in the array. Write overloaded versions of this method that work with int and doubles.
-getAverage =this method should accept a 1D array as its argument and return the average of the values in the array. Write overloaded versions of this method that work with int and doubles.
-getHighest =this method should accept a 1D array as its argument and return the hightest of the values in the array. Write overloaded versions of this method that work with int and doubles.
-getLowest =this method should accept a 1D array as its argument and return the lowest of the values in the array. Write overloaded versions of this method that work with int and doubles.
Test with an array of int(size 10) and an array of doubles(size 8)
Explanation / Answer
public class ArrayOperations{
public static int getTotal(int[] n)
{
int total=0;
for(int i=0;i<n.length;i++)
total+=n[i];
return total;
}
public static double getTotal(double[] n)
{
double total=0.0;
for(int i=0;i<n.length;i++)
total+=n[i];
return total;
}
public static int getAverage(int[] n)
{
return getTotal(n)/(n.length-1);
}
public static double getAverage(double[] n)
{
return getTotal(n)/(n.length-1);
}
public static int getHighest(int[] n)
{
int max=0;
for(int i=0;i<n.length;i++)
if(max<n[i])
max=n[i];
return max;
}
public static double getHighest(double[] n)
{
double max=0;
for(int i=0;i<n.length;i++)
if(max<n[i])
max=n[i];
return max;
}
public static int getLowest(int[] n)
{
int min=9999999;
for(int i=0;i<n.length;i++)
if(min>n[i])
min=n[i];
return min;
}
public static double getLowest(double[] n)
{
double min=99999;
for(int i=0;i<n.length;i++)
if(min>n[i])
min=n[i];
return min;
}
public static void main(String []args){
System.out.println("Testing class");
int n[]={1,2,3,4,5,6,7,8,9,0};
double a[]={1.0,2.0,3.0,4.0,5.0,6.0};
System.out.println("Total "+ArrayOperations.getTotal(n));
System.out.println("Total "+ArrayOperations.getTotal(a));
System.out.println("Avg "+ArrayOperations.getAverage(n));
System.out.println("Avg "+ArrayOperations.getAverage(a));
System.out.println("Max "+ArrayOperations.getHighest(n));
System.out.println("Max "+ArrayOperations.getHighest(a));
System.out.println("Min "+ArrayOperations.getLowest(n));
System.out.println("Min "+ArrayOperations.getLowest(a));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.