I compare two Strings and I do not get into the IF

1
System.out.println("Dime el tablero al que te quieres conectar :");

tablero = sc.nextLine(); // AQUI LO LEO COMO UN STRING EN EL CLIENTE

tablero = tablero.trim();

byte buffer_tablero[];

buffer_tablero = tablero.getBytes();

DatagramPacket mensaje_tablero = new DatagramPacket(buffer_tablero, buffer_tablero.length, InetAddress.getLocalHost(), 50000);


puerto.send(mensaje_tablero); // Aqui envio el mensaje con el numero de tablero al que me quiero conectar


//------------------------------------------------------------------------------

puerto.receive(tablero);
buffer = tablero.getData();
datos = new String(buffer, buffer.length); // AQUI PASO A STRING LO QUE RECIBO DEL PAQUETE

System.out.println("He recibido una peticion para el tablero " + datos);

//-------------------------------------------------------------------------------
if (datos.equals("1") || datos.equals("2") || datos.equals("3")) {}

In this if it does not enter me sending from the client any of these 3 values. Debugueando I look at the value of the variable and it has the same value, when it reaches the if it does not enter.

    
asked by Ruben Gil Gomez 13.12.2016 в 20:00
source

2 answers

0

If the variable datos is of type String even if it is an object ( new String() ), it is difficult not to comply with the sentence, possibly your variable datos contain space (s):

if (datos.trim().equals("1") || datos.trim().equals("2") || datos.trim().equals("3")) {
...
... 
    
answered by 13.12.2016 / 20:32
source
0

In java it is best to use the equals function when it is a string within the if.

But Wait

To be completely sure of what you are going to compare if it is a String, as a good practice of programming it is better that you compare in the following way.

if (("1".equals(datos)) || ("2".equals(datos)) || ("3".equals(datos))) {}

Now why I say that to be completely sure that it is a String , because if you compare the data sent to you with the string to compare. The data sent to you may come as null , if you see. In your case if you compare like this:

if ((datos.equals("1")) || (datos.equals("2")) || (datos.equals("3"))) {}

The data variable may come as null so once the condition is not met.

Now if you do as I say, you're completely sure that the ones you're going to compare is a string with anything else that is supposed to be a string.

Greetings

    
answered by 14.12.2016 в 18:47