Reputation: 11
For a program I have to write I am required to turn a 2 dimensional array of single digit intgers into a string of numbers separated by spaces. A test code is provided for me and when I run it, my code fails both arrayToString tests. I am unable to find where my logic error is. Someone help!
public static String arrayToString(int[][] a) {
String aString;
aString = "";
int column;
int row;
for (row = 0; row < a.length; row++) {
for (column = 0; column < a[0].length; column++ ) {
aString = aString + " " + a[row][column];
}
aString = aString + "\n";
}
return aString;
}
Upvotes: 0
Views: 13961
Reputation: 2137
@dawood-ibn-kareem explain good the possible cause of the failure of the test.
With Java 8 Stream, it's pretty easy to do what you want!
With the input: [[1,2,3], [3,4,5], [5,6,7]]
public static String arrayToString(int[][] a) {
return Arrays.stream(a)
.map(s -> Arrays.stream(s)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" "))
)
.collect(Collectors.joining("\n"));
}
Output:
1 2 3
3 4 5
5 6 7
Other method, to separate each line of the 2D array without carriage return
public static String arrayToString(int[][] a) {
return Arrays.stream(a)
.flatMapToInt(Arrays::stream)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" "));
}
Output
1 2 3 3 4 5 5 6 7
Have fun!
Upvotes: 0
Reputation: 630
int[][] a = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
public static String arrayToString(int[][] a) {
String aString;
aString = "";
int column;
int row;
for (row = 0; row < a.length; row++) {
for (column = 0; column < a[0].length; column++ ) {
aString = aString + " " + a[row][column];
}
aString = aString + "\n";
}
return aString;
}
Output:
1 2 3
4 5 6
7 8 9
If you skip this line aString = aString + "\n";
your output will look like this
1 2 3 4 5 6 7 8 9
Upvotes: 0
Reputation: 79838
I can think of three possible issues.
Until you post the test code, we can't see which one the problem is. But you could deal with all three by changing your loop to this.
for (row = 0; row < a.length; row++) {
if (a[row] != null && a[row].length > 0) {
aString = aString + a[row][0];
for (column = 1; column < a[row].length; column++) {
aString = aString + " " + a[row][column];
}
}
aString = aString + "\n";
}
Upvotes: 0
Reputation: 425033
Your code is basically OK, except you are putting a leading space at the start of every line. To clean them up before returning, add this line:
aString = aString.replaceAll("(?m)^ ", "");
This uses regex to delete (by replacing with a blank) all spaces at the start of lines. The regex flag (?m)
makes ^
match the start of every line of the input (normally ^
matches only the start of input).
Upvotes: -1