0

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.

mancini13
  • 35
  • 1
  • 10
  • Can you give us example of input and expected output? BTW when we iterate we usually use element we got from array in current iteration (`dobule i`) not entire array. – Pshemo Nov 15 '15 at 14:05

2 Answers2

2

Just use Arrays.toString(array).

M A
  • 71,713
  • 13
  • 134
  • 174
0

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
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • How can i do this on double[][] matrix method. In double[][] matrix the String contains a separate line for each row of the matrix – mancini13 Nov 15 '15 at 14:44
  • You'll have to use a loop in this case. Like for (double[] d : matrix) and use Arrays.toString() and a StringBuilder(). I'm editing the answer. – Yassin Hajaj Nov 15 '15 at 14:58