I was trying to code AVL tree in java and something has just shaken my understanding of basic programming. Why does Java force me to return a value when I already have a return statement in the else block of the if-else ladder. I tried debugging and it works as expected, it never goes to the returns statement outside the if-else blocks. I have been working on java and never realized this. I am not even sure if this was always there or is it something new? I also read a few blogs which say that you don't have to return a value if you have returned it from the else block.
The error which I get is I skip the last return statement.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type AVLNode
https://javahungry.blogspot.com/2019/12/missing-return-statement-in-java.html checkout the last example on this link.
public class AVL
{
AVLNode root;
private AVLNode insert ( AVLNode current,int val)
{
if ( current == null)
{
return new AVLNode(val, 0, null, null);
}
else if ( val < current.val)
{
current.left = insert ( current.left, val);
}
else if ( val > current.val)
{
current.right = insert ( current.right, val);
}
else
{
return current;
}
return current; // I don't want to return you ////
}
public void add ( int val)
{
this.root = insert ( this.root, val);
}
Aucun commentaire:
Enregistrer un commentaire