1

The following code:

public static void print(ListNode p)
{
    System.out.print("[");
    if(p==null);
    {
        System.out.println("]");
        return;
    }
    ListNode k = p.getNext();
    //more code
}

causes the following compile error:

 ----jGRASP exec: javac -g Josephus_5_Rajolu.java

Josephus_5_Rajolu.java:53: error: unreachable statement
            ListNode k = p.getNext();
                     ^
1 error

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

Why is that happening? I am only returning if p = null. I want to do my other code if p!=null. Why is it unreachable?

golddove
  • 1,165
  • 2
  • 14
  • 32
  • Lessons to learn: (1) it is easy to write code that does something other than what you think it does, (2) your coding style can help your code to be cleaner. For example, if you placed your curly braces immediately to the right of the if statement you can reduce the chances you'll insert an incorrect simicolon. – Kevin Sitze Nov 13 '12 at 23:59
  • Thanks for the tip. I have seen the curly brace next to the if statement many times and I have tried using it but because I got used to this style of coding, it feels awkward when I try doing that. Lesson 1 is very true. – golddove Nov 22 '12 at 01:20

6 Answers6

12

There's a semicolon after your if statement.

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
3

there is ; after if statement remove it it will work :)

zaffargachal
  • 802
  • 7
  • 21
2

if(p==null); <-- remove the semicolon at the end

Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
2

maybe the ';' at the:
if(p==null);

Barracuda
  • 101
  • 6
1

remove the semicolon after your if

Drew
  • 24,851
  • 10
  • 43
  • 78
1

Where are you instantiating ListNode K?

It looks like to me that the issue is ListNode k is not being instantiated.

I think you need something like this. ListNode k = new ListNode();

Are you creating this within your class?

Also you have a ; after if(p==null); That needs to be removed.