gpt4 book ai didi

java - 在Java中,如果递归方法可以返回混合值,我应该如何声明返回类型?

转载 作者:行者123 更新时间:2023-12-02 07:21:11 25 4
gpt4 key购买 nike

我有以下方法定义,旨在搜索给定键的 JSON 对象并返回该键的 JSONObject 或字符串值。为了确保它搜索 JSON 对象的每个级别,我将其设为递归,但前提是可以返回更深的 JSONObject。编译器提示这必须返回一个对象,因为我已经声明了该返回类型。美好的。在两种情况下,我返回一个对象,但我认为它的问题是在某些情况下它不会返回任何内容。如果我添加最终返回 false 或其他内容,它将通过编译器检查,但对此方法的调用将始终(最终)返回 false 使其无用。我不习惯像Java这样的严格类型语言,所以我以前没有遇到过类似的问题。任何指示将不胜感激。

public Object find(String contentId, JSONObject node) {
JSONObject currentNode = (node != null) ? node : this.txtContent;
Iterator<?> nodeKeys = currentNode.keys();

while ( nodeKeys.hasNext() ){

try {
String key = (String) nodeKeys.next();

if (key.equals(contentId)) {
if (currentNode.get(key) instanceof JSONObject) {
return currentNode.getJSONObject(key);
} else {
return currentNode.getString(key);
}
} else if (currentNode.get(key) instanceof JSONObject) {
find(contentId, currentNode.getJSONObject(key));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}

最佳答案

让我们看看,您应该使用 find 调用返回的值,如果未找到则返回 null:

public Object find(String contentId, JSONObject node) {
JSONObject currentNode = (node != null) ? node : this.txtContent;
Iterator<?> nodeKeys = currentNode.keys();

while ( nodeKeys.hasNext() ){

try {
String key = (String) nodeKeys.next();

if (key.equals(contentId)) {
if (currentNode.get(key) instanceof JSONObject) {
return currentNode.getJSONObject(key);
} else {
return currentNode.getString(key);
}
} else if (currentNode.get(key) instanceof JSONObject) {
Object foundObj = find(contentId, currentNode.getJSONObject(key));
if (foundObj!=null) {
return foundObj;
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return null;
}

关于java - 在Java中,如果递归方法可以返回混合值,我应该如何声明返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14201785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com