javaarraysmethods

Can someone explain what my code means? I'm writing a program that passes user inputs into an array, then calculates the average of the array


The homework assignment is as follows:

 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.

I have written my code and I think it works, but I'm a bit confused on some areas of the homework assignment itself and some areas of my code. Although I wrote two methods, I believe only the double method is being used. Is this correct, or did I misinterpret the assignment?

I also don't really understand some parts of my code. I fiddled around with things until I was able to make it work, but I don't know why some parts worked the way they did.

Here is my code:

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
    }

}

I believe everything is working since I get the correct values when the program is run, but I don't feel like I understand what I did and why. I've asked my professor, but he takes about a week to reply (if he ever does). Thank you for your help!


Solution

  • Although I wrote two methods, I believe only the double method is being used. Is this correct, or did I misinterpret the assignment?

    The main challenge and aim of your assignment is to demonstrate the concept of method overloading in Java.

    Method overloading is a feature that allows multiple methods to have the same name with different parameters.

    The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").

    In your case, you have implemented two methods named average(), one that accepts an array of int and another that accepts an array of double. This exemplifies how Java differentiates between methods not just by their names, but also by their parameter lists.

    As you correctly observed, only the double version is called in your main method. This is because you are passing a double[] array to the average method. Java selects the appropriate average method based on the type of the argument passed. If an int[] array were passed, Java would call the int version of the method.


    A few notes on your code, for your consideration:

    Instead of hard-coding the array length as 10, you could use a variable. That makes your code more adaptable and reusable.
    And I would also avoid hard-coding values like 10 in the loop and average calculation. Use the array's length attribute instead.

    For calculating the sum, you can use an enhanced for loop.

    You are correctly returning the average from both methods, but you are not using these return values in your main method. You can store the returned average in a variable and then print it.

    Consider adding error handling for user input, like checking for invalid inputs (non-numeric, etc.).


    Do you know why I had to initialize sum before the for loop? I tried to initialize it within the for loop, but that didn't work.

    In Java, a variable must be declared and initialized before it is used. When you declare a variable like sum within a loop, its scope (i.e., the part of the code where it is recognized and usable) is limited to that loop.
    Each time the loop iterates, if sum were declared inside it, it would be reinitialized to its starting value, which is not the behavior you want when calculating a sum.

    When you initialize the variable before the loop:

    • int sum = 0; or double sum = 0.0;
    • That line sets up sum with an initial value of 0.
    • The scope of sum is the entire method, meaning it retains its value across all iterations of the loop.
    • Each iteration of the loop adds to sum, accumulating the total.

    When you initialize the variable inside the loop:

    • If sum were declared inside the loop, it would be set to 0 (or any other starting value) at the beginning of each iteration.
    • That means you would lose the total you accumulated in previous iterations.
    // 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
    }
    

    In the correct way, sum is initialized once before the loop starts and retains its value across iterations. In the incorrect way, sum is reset in each iteration, so it never accumulates the total sum of all iterations.


    Why did I need a return statement if I didn't use that return value?

    Even if you do not use the return value of a method in your current program, including a return statement serves multiple purposes:

    • Your method is declared with a return type (int or double), so it must return a value of that type. That is part of fulfilling the contract you have defined in your method's signature.
    • While your current implementation does not use the return value, returning the calculated average makes your method more versatile for future use. For instance, if you later modify your program or use this method in a different program, you might need the average value for further calculations or decision-making processes.
    • And it is a good habit to make sure your methods do exactly what their signature suggests. If a method is supposed to return a value, then it should do so.

    Was I supposed to change "array" in the method header (as stated in the directions) to "userInput", my array name?

    In method headers, the names given to parameters are placeholders. You can name them whatever you like, as long as the names are meaningful and follow Java's naming conventions.
    The name of the parameter in the method definition does not need to match the name of the array you pass to the method when you call it.

    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.
    }
    
    • The names of parameters in method definitions are used within the method to refer to the values passed to it. These names are local to the method and do not affect or depend on the names of variables in other parts of your code.

    • It is often helpful to choose parameter names that are descriptive and indicate their role or the kind of data they represent. Whether you use array, userInput, or any other name, it should ideally convey the purpose or content of the parameter.

    • Changing the parameter name does not affect the functionality of the method. The type of the parameter (int[] or double[]) is what is important. The name is just a label used within the method.

    In your case, using userInput as the parameter name in the method is perfectly fine and might even make the code more readable by clearly indicating that this array is supposed to contain user input. The key is consistency and clarity in how you use these names within the method.