Search code examples
javaarraysstatic-methods

How to use a method to return a double array of user input values?


I want to create a method that returns a double array of user input values. I've figured out how to create a method to ask the user to pick how many elements an array should hold, then pass off the size to next method, which is to spit out a double array of user's input values.

My goal here is to practice learning how to use basic methods (just public static methods) to divide and conquer the problem at hand.

...java package array_exercises; import java.util.Scanner;

public class Array_Exercises {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    // Get number of elements to store values from the user
    int number = numOfElements();

    System.out.println(valueOfElements(number));

}

public static int numOfElements () {
    // Create a Scanner object to get the user's input
    Scanner input = new Scanner (System.in);

    // Get the input from the user
    System.out.print("Enter how many number of the type double do you want"
            + " to store in your array? ");

    return input.nextInt();
}

public static double[] valueOfElements (int num) {
    // Create a Scanner object to get the user's value for each element
    Scanner input = new Scanner (System.in);

    // Declare an array of doubles
    double[] double_array = new double[num];

    // Loop through the elements of double array
    for (int i = 0; i < double_array.length; i++) {
        System.out.print("Enter a value #" + (i + 1) + ": ");
        double_array[i] = input.nextDouble();
    }
    return double_array;
}

}

The expected output should print out all values of the double array in the main method.

All I got was this:

run: Enter how many number of the type double do you want to store in your array? 2 Enter a value #1: 1.234567 Enter a value #2: 2.345678 [D@55f96302

Why is this? What am I doing wrong here? I'm only a beginner, I'm taking a class on Java this semester, so everything is new to me.


Solution

  • An array is an object in java and therefore it is printed by calling its toString() method. This method is not very helpful for the array class and doesn't print the arrays contents. To print the array content you can call Arrays.toString(yourArray) which will return a string representation of the array contents.

    You should replace

    System.out.println(valueOfElements(number));
    

    with

    System.out.println(Arrays.toString(valueOfElements(number)));
    

    and add the following import statement:

    import java.util.Arrays;