0
public ArrayList<String> toTradeArray = new ArrayList<String>();
public String lastTraded = null;
public String needsTraded = null;
public String[] toTrade = new String[toTradeArray.size()];

public void checkTrades() {
    if(s.getTrade().getLastRequestingPlayer() != null) {
        lastTraded = s.getTrade().getLastRequestingPlayer().getName(); 
    }
    toTrade = toTradeArray.toArray(toTrade); 
    for (String i : toTrade)  { 
        if(lastTraded != null) {
            s.log("Last Traded: "+lastTraded.toLowerCase());
            s.log("We need: "+i.toLowerCase());
            if(i.toLowerCase().equals(lastTraded.toLowerCase())) {
            s.log("Correct Player Traded");
            needsTraded = i.toLowerCase(); 
        }
    }   
    }

}

As you can see, my problem is I have two strings that I am comparing, if I try it without spaces it works, but when I try it with spaces, it does not. Why is this?

The stacktraces print & as you can see, they're identical, where in my code did I go wrong?

[INFO][Bot #1][10/27 07:58:15 PM]: We need: test 123
[INFO][Bot #1][10/27 07:58:15 PM]: Last Traded: test 123
  • If you have trailing whitespace (which are hard to see in the output) the strings are not equal. – Thilo Oct 28 '15 at 01:12
  • Are you sure there are no trailing spaces in one of the strings? – lurker Oct 28 '15 at 01:12
  • @Thilo & lurker, will I need to .trim()? – Ethan Brookman Oct 28 '15 at 01:17
  • `trim()` would remove leading and trailing spaces (for some definition of space, http://stackoverflow.com/questions/1437933/). That probably helps. Or it just hides/works around a deeper problem. – Thilo Oct 28 '15 at 01:23

1 Answers1

0

If the spaces are just leading or trailing the string, you can use trim. If you just want to ignore any space within the string, you can use a regular expression to get rid of them. Eg:

    String abcd0 = "  ABCD\n\t";
    String abcd1 = " Ab c\t d\n";
    String abcd2 = "aBcD";
    System.out.println(abcd2.equalsIgnoreCase(abcd0.trim())); // true
    System.out.println(abcd2.equalsIgnoreCase(abcd1.replaceAll("\\s+", ""))); // true

PS: you can use equalsIgnoreCase() instead of converting both strings to lowercase for concise purpose.

Bon
  • 3,073
  • 5
  • 21
  • 40