0

美好的一天,我是 java 新手,我想知道是否有人可以帮助我解决这个问题我有一个服务器,它从客户端接收信息,但是我的 if 语句检查传递的值不起作用。

这是我的服务器代码。

   Session(Socket s){
        soc = s;
        try{
            br = new BufferedReader(new InputStreamReader(soc.getInputStream()));

            pw = new PrintWriter(new BufferedOutputStream(soc.getOutputStream()),true);
            pw.println("Welcome");           
        }catch(IOException ioe){
            System.out.println(ioe);
        }


        if(runner == null){
            runner = new Thread(this);
            runner.start();
        }
    }

    public void run(){
        while(runner == Thread.currentThread()){
            try{
                String input = br.readLine().toString();
                    if(input != null){
                        String output = Protocol.ProcessInput(input);
                        pw.println(output);
                        System.out.println(input);


                        if(output.equals("Good Bye")){
                            runner = null;
                            pw.close();
                            br.close();
                            soc.close();
                        }
                 **This if statement doesn't work   ↓**
                        if(Protocol.ProcessInput(input).equalsIgnoreCase("tiaan")){
                           // System.exit(0);
                            System.out.println("Got tiaan!!!");
                        }
                    }

            }catch(IOException ie){
                System.out.println(ie);
            }
            try{
                Thread.sleep(10);
            }catch(InterruptedException ie){
                System.out.println(ie);
            }
        }
    }


}

class Protocol{
     static String ProcessInput(String input){
        if(input.equalsIgnoreCase("Hello")){
            return "Well hello to you to";
        }else{
            return "Good bye";
        }
    }
}
4

1 回答 1

2

好的。让我们看一下 if 语句:

if(Protocol.ProcessInput(input).equalsIgnoreCase("tiaan")){
    // System.exit(0);
    System.out.println("Got tiaan!!!");
}

该代码等效于以下内容:

String output = Protocol.ProcessInput(input)
if(output.equalsIgnoreCase("tiaan")){
    // System.exit(0);
    System.out.println("Got tiaan!!!");
}

因此,将输出ProcessInput与字符串“tiaan”进行比较,ProcessInput结果表明它永远不会返回该字符串。因此,也许您实际上想做其他事情,例如直接将输入与“tiaan”进行比较或更改以下实现ProcessInput

if(input.equalsIgnoreCase("tiaan")){
    // System.exit(0);
    System.out.println("Got tiaan!!!");
}

请注意,当您读取输入时,您可以获得 NullPointerException:

//Change this:
String input = br.readLine().toString();
//Into this:
String input = br.readLine();

readLine已经给了你一个字符串,所以你最后不需要 toString 。如果readLine给你 null,当你到达流的末尾时它会这样做,那么调用toString将导致 NullPointerException。在下一行,您实际上检查输入是否为空,这很好,但使用您的代码,错误将在该检查之前发生。

于 2013-05-22T08:05:49.953 回答