我正在尝试使用数组参数创建不同的构造函数。数组具有不同的维度。但实际上在任何时候调用二维构造函数。
public Network(String [] adjacentMatrixRows) throws AdjacentMatrixCreationExeption {
this.adjacentMatrix = new int[adjacentMatrixRows.length][];
String [][] stringMatrix = new String[adjacentMatrixRows.length][];
for (int i = 0; i < adjacentMatrixRows.length; i++) {
stringMatrix[i] = adjacentMatrixRows[i].trim().split(" ");
this.adjacentMatrix[i] = new int[stringMatrix[i].length];
}
for (int i = 0; i < stringMatrix.length; i++){
for (int j = 0; j < stringMatrix[i].length; j++) {
try {
this.adjacentMatrix[i][j] = Integer.parseInt(stringMatrix[i][j]);
}
catch (NumberFormatException e){
throw new AdjacentMatrixCreationExeption("Wrong data format in String[].");
}
}
}
}
public Network(String[][] adjacentMatrix) throws AdjacentMatrixCreationExeption {
this.adjacentMatrix = new int [adjacentMatrix.length][];
for (int i = 0; i < adjacentMatrix.length; i++){
this.adjacentMatrix[i] = new int[adjacentMatrix[i].length];
for (int j = 0; j < adjacentMatrix[i].length; j++) {
try {
this.adjacentMatrix[i][j] = Integer.parseInt(adjacentMatrix[i][j]);
}
catch (NumberFormatException e){
throw new AdjacentMatrixCreationExeption("Wrong data format in String[][].");
}
}
}
}
可能是问题引起的,因为数组由数组组成。但我该如何解决呢?
UPD: 我试图在Junit测试中调用构造函数:
` Throwable exception = assertThrows(AdjacentMatrixCreationExeption.class, ()-> {
Network network = new Network(new String [][]{{"1", "a"},{"1", "1"}});});
assertEquals("Wrong data format in String[][].", exception.getMessage());`
Throwable exception2 = assertThrows(AdjacentMatrixCreationExeption.class, ()-> {
Network network = new Network(new String []{"1", "a", "1", "1"});});
assertEquals("Wrong data format in String[].", exception.getMessage());
JUnit测试的输出:
org.opentest4j.AssertionFailedError: expected: <Wrong data format in String[].> but was: <Wrong data format in String[][].>
Expected :Wrong data format in String[].
Actual :Wrong data format in String[][].
答案 0 :(得分:1)
我在下面进行了测试
public class Test {
public static void main(String[] args) {
String[] array = new String[1];
String[][] array2D = new String[1][1];
Network n1 = new Network(array);
Network n2 = new Network(array2D);
}
}
这是具有两个构造函数的网络类:
class Network {
public Network (String [] adjacentMatrixRows){
System.out.println("Array");
}
public Network (String [][] adjacentMatrixRows){
System.out.println("2D Array");
}
}
我得到了以下输出:
阵列
2D数组
答案 1 :(得分:0)
我找到了答案!在我的JUnit测试中,我总是使用一个名为“exception”的异常。但在第二次测试中,我不得不使用“exception2”
$answer1 = $answers->where('answer_1', 1)->count();
$answer2 = $answers->where('answer_1', 2)->count();
...
感谢大家。问题已经解决了。