I have to implement a static-public method named “
berechneMittelwertWurzel
”. The method gets as input parameters a double array and two integer values and returns a double value. Signature: calculateMeanRoot(double[] array, int startindex, int endindex) : double The method calculates the mean value from the numbers in the array in the specified range (startIndex to endIndex). From the mean value the square root is calculated and returned.
negative values for both indexes are to be neglected
Is there a better way to this ?
public static double [] berechneMittelwertWurzel(int startindex, int endindex) {
double arr[] = { 5.2, 66.23, -4.2, 0.0, 53.0 };
double sum = 0;
for(int i=0; i<arr.length; i++){
sum = sum + arr[i];
double average = sum / arr.length;
for(int i =0; i < arr.length;i++)
{
for(int j = 0;j < arr.length;j++)
{
if(Math.sqrt(arr[i]) == arr[j])
{
s += arr[j] + "," + arr[i] + " ";
if(index < 0 || index >= array.length)
throw new IndexOutOfBoundsException();
The function you’ve posted does not conform to the specification from the exercise. There are various problems:
In addition, your question title mentions the median; however, you’re attempting to calculate the arithmetic mean. Judging from the question text, this might actually be correct. Just be aware that these two values are generally different.
To fix this, start off from the following signature and fill in the gaps:
public static double calculateMeanRoot(double[] array, int startindex, int endindex) {
// if the startIndex > endIndex is an IntervalException should be thrown
// if the endIndex > array.length -1 or startIndex < 0, the IndexOutOfBoundsException shall be thrown
// calculate the sum of the array elements between `startIndex` and `endIndex` (*)
// calculate the mean by dividing the sum by the difference between `endIndex` and `startIndex`
// if the calculated mean is less than zero (<0), then a NegativeNumberException shall be thrown with an output
// calculate the square root of the mean, round it, and return it
}
Only the step annotated with (*)
requires a loop.