-2

I have an array:

int A = {1,2,3,4,5,6};

I would like to display it on phone screen as a single string 123456 (or 1 2 3 4 5 6) (i.e. with a space between each number. Could you please help to let me know how to do it?

pb2q
  • 58,613
  • 19
  • 146
  • 147
notebook
  • 29
  • 2
  • 6

3 Answers3

1

Shortcut:

String line = "";
for(int temp : A) {
    line = line + (""+temp);
}
System.out.println(line);
Plasma
  • 1,903
  • 1
  • 22
  • 37
0

You could use a combination of loop and StringBuilder:

Note, using StringBuilder is greatly recommended when dealing with String and String concatenation in a loop process. Read this for reference: StringBuilder vs String concatenation in toString() in Java

int[] A = new int[]{1,2,3,4,5,6};
StringBuilder sb = new StringBuilder();
for(int ctr = 0; ctr < A.length; ctr++){
    sb.append(A[ctr]);

    //print separator only when there are items after this one.
    if(ctr < A.length -1){
        sb.append(", ");
    }
}

System.out.println(sb.toString());
Community
  • 1
  • 1
ariefbayu
  • 21,849
  • 12
  • 71
  • 92
0

If only printing is the issue, then why not do it in a simple way,

for(int i = 0; i < A.length; i++){
    System.out.print(A[i]);//not println
}
System.out.println();//just add an extra line.

Another can be, Arrays.toString(A)//verify this.

P basak
  • 4,874
  • 11
  • 40
  • 63