Reputation: 1
Good day all i am new to java and i would like to know if someone can help me with this problem I have a server and it receives info from the client but my if statement to check the value that was passed doesn't work.
Here is my code for the server.
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";
}
}
}
Upvotes: 0
Views: 101
Reputation: 1180
Ok. Let's have a look at that if statement:
if(Protocol.ProcessInput(input).equalsIgnoreCase("tiaan")){
// System.exit(0);
System.out.println("Got tiaan!!!");
}
That code is equivalent to the following:
String output = Protocol.ProcessInput(input)
if(output.equalsIgnoreCase("tiaan")){
// System.exit(0);
System.out.println("Got tiaan!!!");
}
So the output from ProcessInput
is compared to the string "tiaan" and looking at ProcessInput
shows that it will never return that string. So maybe you actually want to do something else, for example compare the input directly with "tiaan" or change the implementation of ProcessInput
:
if(input.equalsIgnoreCase("tiaan")){
// System.exit(0);
System.out.println("Got tiaan!!!");
}
Note that you can get a NullPointerException when you read the input:
//Change this:
String input = br.readLine().toString();
//Into this:
String input = br.readLine();
readLine
already gives you a string so you don't need toString at the end. If readLine
gives you null, which it does when you reach the end of the stream, then the invocation of toString
will cause a NullPointerException. On the next line you actually check if input is null which is good but using your code the error will occur before that check.
Upvotes: 2