无法在Java中计算数组的平均变化

时间:2018-11-01 02:03:03

标签: java arrays

因此,我必须编写一个代码,允许用户计算他们每周运行的平均里程变化,但遇到一些问题,希望能获得一些指导。该程序基本上允许用户输入他们拥有多少周的数据以及所有对应的里程值,并将这些值存储在数组中。我认为我真的很接近,但是由于某种原因,当我尝试计算数组中所有值的差之和时,它只存储了数组中前两个值之间的差,而没有存储其余两个值,因此给了我一个不正确的信息结果。特别是这部分代码是我遇到问题的地方:

sumOfDifferences += (y[i+1] - y[i]); 
average = (sumOfDifferences) / (weeksData - 1);

这是我到目前为止所拥有的。感谢您能获得的任何帮助

import java.util.Scanner;

public class RunAnalyzer
{
    public static void main(String[]args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("\n How many weeks of data do you have? ");

            int weeksData = input.nextInt();        

        double [] y = new double [weeksData];       double average = 0;     double sumOfDifferences = 0;    
        for (int i = 0; i < y.length; i++) 
        {

            System.out.print("\nEnter miles run for week " + (i + 1) + ": ");

                y[i] = input.nextDouble();


        }

            for  (int i = 0; i < y.length; i++)
            {
                sumOfDifferences += (y[i+1] - y[i]); 
                average = (sumOfDifferences) / (weeksData - 1);

                if (y[i+1] <= y[i])
                {
                    System.out.print("\n You're weekly mileage is NOT increasing!");

                    break;
                }

                else
                {
                    System.out.println("Your weekly mileage is increasing!");

                    break;
                } 


            }

            System.out.print("\nAverage weekly mileage change: " + average);

    }

}

1 个答案:

答案 0 :(得分:1)

问题在于,在第一次迭代中,您NO处于循环之外。 (您的breakif都有休息时间,因此无论走哪条路都会中断):

else

您将要删除它们。但是,一旦完成,您将得到一个for (int i = 0; i < y.length; i++) { sumOfDifferences += (y[i+1] - y[i]); average = (sumOfDifferences) / (weeksData - 1); if (y[i+1] <= y[i]) { System.out.print("\n You're weekly mileage is NOT increasing!"); break; } else { System.out.println("Your weekly mileage is increasing!"); break; } } 错误,就像在上一次迭代中,当ArrayIndexOutOfBounds等于y[i + 1]时,您将调用i。这将不是有效的索引。您只想迭代到y.length -1

<y.length-1