Search code examples
javaarraysstringdouble

How can i build and return a String that contains the elements in an array?


i need an overloaded method that uses enhanced for loops to build and return a String that contains the elements in an array. This is my work:

 public static String arrayToString(double[] dblArray) {
    String str = "";
    for (double i : dblArray) {
        System.out.println(dblArray.toString());
    }
    return str;
  }

And i got output something like this:

 [D@232204a1
 [D@232204a1
 [D@232204a1
 [D@232204a1

I think this is adress of array's elements.


Solution

  • Solution

    public static String arrayToString(double[] dblArray) {
        String arr = Arrays.toString(dblArray);
        String fin = arr.substring(1,arr.length()-1).replace(",", " ");
        return fin;
    }
    

    Here is a solution without using a loop.


    Input

    {5.12,3.14,5.6}
    

    Output

    5.12  3.14  5.6
    

    EDIT

    If you also want to use a method to print a 2D array with the same technique, you'll have to use a enhanced loop like below.

    Solution

    public static String arrayToString(double[][] dblArray) {
            StringBuilder fin = new StringBuilder();
            for (double[] d : dblArray){
                fin.append(Arrays.toString(d).replace("[", "").replace("]", "").replace(",", " ") + "\n");
            }
            return fin.toString();
        }
    

    Input

    {{3.14,2.35}, {3.14,2.35}, {3.14,2.35}}
    

    Output

    3.14  2.35
    3.14  2.35
    3.14  2.35