• Post Reply Bookmark Topic Watch Topic
  • New Topic

error: missing return statement  RSS feed

 
Ronald Spina
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm having a problem with the below method. I have implemented my own queue based on a singly linked list. This method returns the node at the head. The problem was that when the queue is empty the program will halt therofore I added a base case on the second part of code, adding a base case however is giving me the above error message. Can any one tell me were I am making the mistake. Thank you.

Before: Code without base case, worked fine expect when queue is empty.



After: Added base case however giving error.
 
Joel Christophel
Ranch Hand
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ronald Spina wrote:


As far as syntactical logic is concerned here's what's wrong: the compiler determines that the return statement possibly won't be reached since it's in an else statement. Also, you will also get an error if temp isn't initialized anywhere other than the if statement because what will be returned if temp's initialization is never reached? Also instead of if(head==null) and having it empty, use if(head!=null). So this is how you would write that:



EDIT: However, the above probably does the same as the first code example you posted. Basically, if you're going to return temp, you're going to have to accept the fact that sometimes you'll be returning a null value. What you may need to do is use your first code example ( but remove temp.printList() ) and then use a try/catch block when calling dequeue():

 
Ronald Spina
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your immediate reply. I have understood my mistake. The return statement should not be in the "if or else" statements but outside. A was able to run the program successfully with both the below methods.

Method 1

Method 2

 
Ronald Spina
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks once again. Yes, the last method you posted with the try catch is a good idea. I still have to learn how to simplify my code. Practice makes perfect :
Thanks.
 
Joel Christophel
Ranch Hand
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ronald Spina wrote:Thanks once again. Yes, the last method you posted with the try catch is a good idea. I still have to learn how to simplify my code. Practice makes perfect :
Thanks.


I'm glad I could be of assistance.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!