Cri*_*bæk -1 java recursion return-value
我有一个递归方法,我想在特定的 if 语句返回 true 时返回一个值(它总是这样做)
if (compactArray != null) {
if (arrayCount == (compactArray[0].length - 1)) {
return compactArray;//i want to return here
}
}
Run Code Online (Sandbox Code Playgroud)
但 Java 不会让我从 if 返回,并抛出警告,提示我需要添加返回值。
一个人做什么?完整方法如下
public String[][] diXmlRecursiveRead(Iterator<Element> list, String[] columnNames, String[][] compactArray,
Integer arrayCount) {
Element element = null;
String[] columns = null;
while (list.hasNext()) {
element = list.next();
// Assign data to the two dimensional array, starting from position
// 1 in the length to not overwrite the column names.
// This is also where i would print the column name plus its
// attribute value if i was printing to console.
if (columnNames != null) {
for (int a = 0; a < columnNames.length; a++) {
compactArray[a][arrayCount] = element.getAttributeValue(columnNames[a]);
}
}
// Find the element that contains the columns="" information
if (element.getAttributeValue("columns") != null) {
// reset the array count, since we are processing a new
// columns="" section
arrayCount = 1;
columns = element.getAttributeValue("columns").toString().split(",");
// set width size +1 to make room for the column names
// (columnNames + data +1)
compactArray = new String[columns.length][element.getChildren().size() + 1];
// Set the EVE column names in the first column of the two
// dimensional array
for (int a = 0; a < columns.length; a++) {
compactArray[a][0] = columns[a];
}
}
// After added the last value to the two dimensional array return the
// array[][]
if (compactArray != null) {
if (arrayCount == (compactArray[0].length - 1)) {
return compactArray;//i want to return here and not at the end!
}
}
// Method calls itself with a new level of the child
diXmlRecursiveRead(element.getChildren().iterator(), columns, compactArray, arrayCount++);
}
//Java want me to return here!!
}
Run Code Online (Sandbox Code Playgroud)
小智 6
看那个例子:
static int count = 0;
private static boolean foo() {
if (count == 5) {
return true;
}
count ++;
return foo();
}
Run Code Online (Sandbox Code Playgroud)
请注意,递归调用是使用“return”语句调用的。
考虑一下执行递归方法时正在构建的堆栈。在某些时候,所有方法都需要开始在堆栈上返回一个值。