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?
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?
Shortcut:
String line = "";
for(int temp : A) {
line = line + (""+temp);
}
System.out.println(line);
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());
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.