please help I cannot figure out what im doing wrong. I am in a basic computer sc
ID: 3553318 • Letter: P
Question
please help I cannot figure out what im doing wrong.
I am in a basic computer science class so it is nothing to advanced.
I finished maost of the program I just need help where it says add code here.
please help.
import java.util.*;
public class Lab9b
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int averageLength = scan.nextInt();
int numDataPoints = scan.nextInt();
double data[] = new double[numDataPoints];
double movingAverage[] = new double[numDataPoints];
for(int i=0; i<=numDataPoints; i++)
{
//[add code here]
}
printArray(data);
System.out.println();
for (int i=0; i<numDataPoints; i++)
{
movingAverage[i] = computeMovingAverage(data, averageLength, i);
}
printArray(movingAverage);
}
public static void printArray(double[] arr)
{
// Print the values of arr on a single line with spaces between them.
// [Add code here]
}
public static double computeMovingAverage(double[] data, int
averageLength, int i)
{
// Calculate and return the moving average for index i
// (Hint: you need a for loop to do this. Make sure to handle the
// case where i is not large enough (when i<averageLength-1)).
// [Add code here]
}
}
Explanation / Answer
import java.util.*;
public class Employee
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int averageLength = scan.nextInt();
int numDataPoints = scan.nextInt();
double data[] = new double[numDataPoints];
double movingAverage[] = new double[numDataPoints];
for(int i=0; i<numDataPoints; i++)
{
data[i]=scan.nextInt();
}
printArray(data);
System.out.println();
for (int i=0; i<numDataPoints; i++)
{
movingAverage[i] = computeMovingAverage(data, averageLength, i);
}
printArray(movingAverage);
System.out.println();
}
public static void printArray(double[] arr)
{
// Print the values of arr on a single line with spaces between them.
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
public static double computeMovingAverage(double[] data, int averageLength, int i)
{
// Calculate and return the moving average for index i
// (Hint: you need a for loop to do this. Make sure to handle the
// case where i is not large enough (when i<averageLength-1)).
if(i<(averageLength-1))
return -1.0; // Return -1 when i is not large enough
double sum=0;
for(int index=i;index>=(i-(averageLength-1));index--)
{
sum=data[index]+sum;
}
return sum/averageLength;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.