For this application a command comes in from the user and the server sends back a reply. The if statement is not working for some reason and for every input it runs sentance = "Unknown Command" + '\n';. I was wondering what I’m doing wrong.
import java.io.*;
import java.net.*;
// SERVER
class StartingPoint {
public static void main(String argv[]) throws Exception{
double srvversion = 0.1;
double cliversion = 0.1;
String clientSentence;
String sentance = null;
String capitalizedSentence;
//Commands cmds = new Commands();
ServerSocket welcomeSocket = new ServerSocket(6789);
System.out.println("Server Started");
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase();
if(capitalizedSentence == "VERSION"){
sentance = "Current Server Version: " + srvversion
+ " | Current Client Version: " + cliversion + '\n';
}else{
sentance = "Unknown Command" + '\n';
}
outToClient.writeBytes(sentance);
System.out.println("Sent: " + sentance);
}
}
}
You should use .equals() method for comparing strings instead of using ==.
Change
to