java 有人能解释一下我的代码是什么意思吗?我正在写一个程序,它把用户输入传递到一个数组中,然后计算数组的平均值

ssm49v7z  于 6个月前  发布在  Java
关注(0)|答案(1)|浏览(34)

家庭作业如下:

Write two overloaded methods that return the average of an array with the following headers:

  **public static int average(int\[\] array)**

  **public static double average(double\[\] array)**

 Write a test program that prompts the user to enter ten double values, invokes this method, and displays the average value.

字符串
我已经写了我的代码,我认为它可以工作,但是我对作业本身的某些区域和我的代码的某些区域有点困惑。虽然我写了两个方法,但我相信只有double方法被使用。这是正确的吗?或者我误解了作业?
我也不太理解我的代码的某些部分,我摆弄了一些东西,直到我能够使它工作,但我不知道为什么有些部分工作的方式。
下面是我的代码:

import java.util.Scanner; //Scanner is used to allow user input

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

        double[] userInput = new double[10];// creates an array called userInput with 10 doubles in that array

        System.out.printf("Please input 10 numbers: ");
        for (int i = 0; i < 10; i++) {
            userInput[i] = input.nextDouble();// the next input will be added to the userInput array in location i
        }

        average(userInput); // calls the method average and passes the userInput array to that method

        input.close(); // close input to prevent resource leak
    }

    public static int average(int[] userInput)
    // userInput is necessary at end to make it accessible for the following
    // statements (Is this correct? The assignment said the header should include
    // "array)", but I'm not sure whether this is something I'm supposed to fill in
    // with my array name or something I should have left alone.)
    {
        int sum = 0;
        // necessary so sum can be used in following for statement, not sure why I
        // couldn't initialize below with int sum = userInput[]i + sum;

        for (int i = 0; i < 10; i++) {
            sum = userInput[i] + sum;
        }
        int average = sum / 10;

        System.out.printf("%nThe average of your values is %d.%n%n", average);
        return average; // necessary but not sure why
    }

    public static double average(double[] userInput)
    // userInput is necessary at end to make it accessible for the following
    // statements (Is this correct? The assignment said the header should include
    // "array)", but I'm not sure whether this is something I'm supposed to fill in
    // with my array name or something I should have left alone.)
    {
        double sum = 0;
        // necessary so sum can be used in following for statement, not sure why I
        // couldn't initialize below with double sum = userInput[]i + sum;

        for (int i = 0; i < 10; i++) {
            sum = userInput[i] + sum;
        }
        double average = sum / 10;

        System.out.printf("%nThe average of your values is %.2f.%n%n", average);
        return average; // necessary but not sure why
    }

}


我相信一切都在工作,因为我得到正确的值时,程序运行,但我不觉得我明白我做了什么,为什么。我已经问过我的教授,但他需要大约一个星期的答复(如果他曾经这样做)。谢谢你的帮助!

plupiseo

plupiseo1#

虽然我写了两个方法,但我相信只有double方法被使用了。这是正确的,还是我误解了赋值?
作业的主要挑战和目标是演示method overloading in Java的概念。
方法重载是一个特性,它允许多个方法具有相同的名称和不同的参数。
Java编程语言支持重载方法,并且Java可以区分不同方法签名的方法,这意味着如果类中的方法有不同的参数列表,它们可以有相同的名称(这方面的一些限制将在标题为“接口和继承”的课程中讨论)。
在本例中,您实现了两个名为average()的方法,一个接受int数组,另一个接受double数组。这说明了Java如何不仅通过名称,而且还通过参数列表来区分方法。
正如你正确观察到的,在你的main方法中只调用double版本。这是因为你正在向average方法传递一个double[]数组。Java根据传递的参数类型选择适当的average方法。如果传递了一个int[]数组,Java将调用该方法的int版本。
关于你的代码的几点注意事项,供你参考:
你可以使用一个变量,而不是硬编码数组长度为10。这使你的代码更具适应性和可重用性。
我也会避免在循环和平均计算中硬编码像10这样的值,而是使用数组的length属性。
要计算sum,可以使用enhanced for loop
您正确地从两个方法中返回了平均值,但您没有在main方法中使用这些返回值。您可以将返回的平均值存储在变量中,然后打印它。
考虑为用户输入添加错误处理,例如检查无效输入(非数字等)。
你知道为什么我必须在for循环之前初始化sum吗?我试着在for循环中初始化它,但那不起作用。
在Java中,变量必须在使用之前声明并初始化。当您在循环中声明像sum这样的变量时,its scope(即,它被识别和可用的代码部分)仅限于该循环。
每次循环迭代时,如果在循环中声明了sum,它将被重新初始化为初始值,这不是计算总和时想要的行为。
在循环之前初始化变量时:

  • int sum = 0;double sum = 0.0;
  • 这一行设置了sum,初始值为0。
  • sum的作用域是整个方法,这意味着它在循环的所有迭代中都保持其值。
  • 循环的每一次迭代都与sum相加,累加总数。

当你在循环中初始化变量时:

  • 如果在循环中声明了sum,则在每次迭代开始时它将被设置为0(或任何其他起始值)。
  • 这意味着您将丢失在先前迭代中累积的总数。
// Correct way
int sum = 0;
for (int i = 0; i < 10; i++) {
    sum += i; // Adds i to sum, accumulating over each iteration
}

// Incorrect way
for (int i = 0; i < 10; i++) {
    int sum = 0; // Sum is reset to 0 on each iteration
    sum += i; // Only the current value of i is added, previous totals are lost
}

字符串
在正确的方式下,sum在循环开始前初始化一次,并在迭代过程中保持其值。在不正确的方式下,sum在每次迭代中重置,因此它永远不会累计所有迭代的总和。
如果我没有使用那个返回值,为什么我需要一个return语句?
即使在当前程序中不使用方法的返回值,包含return语句也有多种用途:

  • 你的方法声明了一个返回类型(intdouble),所以它必须返回该类型的值。这是履行你在方法签名中定义的契约的一部分。
  • 虽然当前的实现不使用返回值,但返回计算的平均值会使您的方法更通用,以供将来使用。例如,如果您以后修改程序或在其他程序中使用此方法,则可能需要平均值来进行进一步的计算或决策过程。
  • 确保你的方法完全按照它们的签名所建议的去做是一个好习惯。如果一个方法应该返回一个值,那么它就应该这样做。

我是否应该将方法头中的“array“(如说明中所述)更改为“userInput“,即我的数组名?
在方法头中,给参数的名字是占位符。你可以给它们起任何你喜欢的名字,只要名字有意义并且遵循Java的命名约定。
方法定义中参数的名称不需要与调用方法时传递给该方法的数组的名称相匹配。

public static double average(double[] array) {
    // The name 'array' here is just a label for whatever double array is passed to this method.
    // It could be named 'data', 'values', 'input', etc.
}

  • 方法定义中的参数名称在方法中用来引用传递给它的值。这些名称是方法的本地名称,不会影响或依赖于代码其他部分中的变量名称。

  • 选择描述性的参数名通常会很有帮助,并表明它们的作用或它们代表的数据类型。无论您使用arrayuserInput还是任何其他名称,它都应该理想地传达参数的目的或内容。

  • 修改参数名不会影响方法的功能。参数的类型(int[]double[])才是重要的。名称只是方法中使用的标签。

在你的例子中,在方法中使用userInput作为参数名是非常好的,甚至可以通过清楚地指示这个数组应该包含用户输入来使代码更具可读性。关键是在方法中如何使用这些名称的一致性和清晰性。

相关问题