Reputation: 13
This has been giving meet a lot of trouble. I don't understand why the test is failing. arrayToString is supposed to take the values of array1 and store it so that it compared to correctAnswer.
public static String arrayToString(int[][] a) {
String string = "";
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[0].length; col++) {
string += a[row][col] + " ";
}
string += "\n";
}
return string;
}
The main method.
public static void main(String[] args){
private static int[][] array1 = {
{3, 2, 1, 1},
{2, 5, 6, 2},
{1, 2, 9, 8}
};
String methodCallResult, correctAnswer;
System.out.println("Testing arrayToString method:");
methodCallResult = FindTheSums.arrayToString(array1);
correctAnswer = "3 2 1 1\n2 5 6 2\n1 2 9 8";
if(methodCallResult.equals(correctAnswer)){
System.out.println("arrayToString(array1) test passed");
}
else{
System.out.println("arrayToString(array1) test failed");
}
}
Upvotes: 0
Views: 72
Reputation: 208984
Test is failing because you have a space after each letter. Here you dont.
correctAnswer = "3 2 1 1\n2 5 6 2\n1 2 9 8";
^^ ^^
string += a[row][col] + " ";
space ^^
This would match
correctAnswer = "3 2 1 1 \n2 5 6 2 \n1 2 9 8 ";
space ^^ space^^ space^^
Edit: possible solution with method change
public static String arrayToString(int[][] a) {
String string = "";
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[0].length; col++) {
if (col == a[0].length - 1) { // add the if statement to check for
string += a[row][col]; // end of row. End of row adds no space.
} else {
string += a[row][col] + " ";
}
}
string += "\n";
}
return string;
}
Upvotes: 1
Reputation: 3073
You are adding a space at the end of the conversion.
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[0].length; col++) {
string += a[row][col] + " ";
^^^
}
string += "\n";
}
Therefore, correctAnswear
should be 3 2 1 1 \n2 5 6 2 \n1 2 9 8;
.
Upvotes: 0