Zarif Shahriar Zarif Shahriar - 1 month ago 8
Java Question

Java String Comparisons

I've been running into a very strange problem while working on a UDP based java project. To sum it up, when I receive a request through a DataPacket I convert it into a new string, then when I go to check the string value it continues to return false. The code is below.

DatagramPacket request = new DatagramPacket(buffer, buffer.length);
aSocket.receive(request);
String message = new String(request.getData());
System.out.println("Received: " + new String(request.getData()));
System.out.println(message); //Prints out "11" without quotes when I send it
String a = "11";
System.out.println("Received: " + message);
if(message.equals("11")){
System.out.println("Got 11.");
}
// Also tried .equals(a), but either ways it seems to be returning false.

Answer

try to trim your message maybe it contains space.

    DatagramPacket request = new DatagramPacket(buffer, buffer.length);
    aSocket.receive(request);
    String message = new String(request.getData()).trim();
    System.out.println("Received: " + new String(request.getData()));
    System.out.println(message); //Prints out "11" without quotes when I send it
    String a = "11";
    System.out.println("Received: " + message);
    if(message.equals("11")){
        System.out.println("Got 11.");
    }  
Comments