Java返回语句优先级
我有以下代码:Java返回语句优先级,java,tree,return,Java,Tree,Return,我有以下代码: private String buscar(Nodo nodo, Nodo raiz) { System.out.println(nivel); this.nivel++; if (raiz != null) { if (nodo.getValor() == raiz.getValor()) { System.out.println("es igual"); return "El númer
private String buscar(Nodo nodo, Nodo raiz) {
System.out.println(nivel);
this.nivel++;
if (raiz != null) {
if (nodo.getValor() == raiz.getValor()) {
System.out.println("es igual");
return "El número " + nodo.getValor() + " está en el nivel: " + this.nivel;
} else if (nodo.getValor() < raiz.getValor()) {
buscar(nodo, raiz.getIzq());
} else {
System.out.println("es mayor");
buscar(nodo, raiz.getDer());
}
} else {
return "El número " + nodo.getValor() + " no forma parte del árbol";
}
return null;
}
public String buscar(int valor) {
this.nivel = 0;
Nodo nodo = new Nodo(valor);
return this.buscar(nodo, this.raiz);
}
private String客车(Nodo Nodo,Nodo raiz){
系统输出打印LN(nivel);
这个.nivel++;
if(raiz!=null){
if(nodo.getValor()==raiz.getValor()){
System.out.println(“es igual”);
返回“elnúmero”+nodo.getValor()+“estáen El-nivel:”+this.nivel;
}else if(nodo.getValor()
始终执行最后一个返回语句(returnnull),即使if语句变为true。有人能告诉我为什么会发生这种情况吗?您需要
返回递归调用的结果,您还可以消除其他条件中的两个(因为您返回
)。而且,我更喜欢String.format
而不是串联。像
private String buscar(Nodo nodo, Nodo raiz) {
System.out.println(nivel);
this.nivel++;
if (raiz != null) {
if (nodo.getValor() == raiz.getValor()) {
System.out.println("es igual");
return String.format("El número %d está en el nivel: %d",
nodo.getValor(), this.nivel);
} else if (nodo.getValor() < raiz.getValor()) {
return buscar(nodo, raiz.getIzq()); // return the recursive result
}
System.out.println("es mayor");
return buscar(nodo, raiz.getDer()); // return the recursive result
}
return String.format("El número %d no forma parte del árbol", nodo.getValor());
}
private String客车(Nodo Nodo,Nodo raiz){
系统输出打印LN(nivel);
这个.nivel++;
if(raiz!=null){
if(nodo.getValor()==raiz.getValor()){
System.out.println(“es igual”);
返回String.format(“El número%d estáen El nivel:%d”,
nodo.getValor(),this.nivel);
}else if(nodo.getValor()
是否因为您仅从以下条件返回:nodo.getValor()==raiz.getValor()
?我想你的意思是改变buscar(nodo,raiz.getIzq())代码>和公共汽车(nodo,raiz.getDer())代码>到返回客车(nodo,raiz.getIzq())代码>和返回客车(nodo,raiz.getDer())代码>?您没有显示Nodo
的代码,您需要进行一些基本调试,逐步检查代码,看看哪里出错。@如果您是对的,我必须在所有选项中使用返回,非常感谢:)