Java if/else behaving strangely

后端 未结 4 724
日久生厌
日久生厌 2021-01-26 18:50

I\'m a real newbie to java, so please excuse me if this is a hopelessly straightforward problem.

I have the following from my java game server:

// Get in         


        
相关标签:
4条回答
  • 2021-01-26 19:36

    From the information added in your comments it seems that what will be happening is the client is sending a single character (e.g. 'n'). The line

    line.substring(0,3).equals("GET")||line.substring(0,4).equals("POST"))
    

    will be executed, but since line is only a single character line.substring(0,3) will throw a StringIndexOutOfBoundsException. Either this is causing your program to fail and you haven't mentioned that. Or you have some exception handling going on in another part of your code that you haven't shown and this is either supressing the error or printing a log line or something and again you haven't mentioned this (or noticed it).

    Try replacing substring().equals with startsWith

    0 讨论(0)
  • 2021-01-26 19:44

    It would seem highly unlikely that the else is not executing. Are you sure your loop does not exit on such packets and hence your conditions do not even run? Does your System.out.println("Received "+line); print anything for the packet that seems to be missing the else statement?

    0 讨论(0)
  • 2021-01-26 19:49
    1. You need to check for null before you trim it. The result of trim() can never be null.

    2. You should check disconnect first, before the readLine(), otherwise you are always doing one readLine() too many.

    3. If you are never getting to your 'else' it means one of the other conditions is always true.

    0 讨论(0)
  • 2021-01-26 19:49

    There are a number of problems with your code

    • in.readLine().trim() readLine do returns null and calling null.trim() will result in ... NullPointerException
    • Is there a reason to append EOF to every response you send.
    • calling substring without making sure it has at least that much elements will throw StringIndexOutOfBoundsException if it is shorter.

    Are you testing with "P" for example?

    0 讨论(0)
提交回复
热议问题