简体   繁体   中英

java string comparison fails?

I'm really puzzled about why this if statement keeps failing. I'm comparing a value and it always returns false.

String userDetail = "john";

 if (sentence.equals(userDetail))
 {

 String returnval = "100%";
 sendData = returnval.getBytes();
 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
 serverConn.send(sendPacket); 
 }
 else
 {
 String returnval = sentence;
 sendData = returnval.getBytes();
 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
 serverConn.send(sendPacket); 
 }

I am positive that "sentence" does equal john. AS you can see I have been doing troubleshooting so in the else statement, I set the return value to sentence and it does return john.

ANy suggestions?

If your variable does appear to equal "john", it is possible that it contains some extra whitespace.

To remove the whitespace in the beginning and end of the string, use:

sentence.trim()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM