-2

Part of a task I'm trying to solve is building all possible combinations of letters and whitespace. I'm trying to find a specific String, while building the combinations. I think i implemented the solution well, but my test tells me otherwise.

I'm taking the chars from an array and in a for loop I build a String from them, then print the solution. When I built all the combinations of let's say "1 character combinations", then i move on to "2 character combinations". I have a boolean to check if the contents of the StringBuilder is equal to the given String that i want to find. I checked, and the example String was indeed built, but the boolean didn't change.

public static void main(String[] args) throws InterruptedException {

    findString("rxc");

}

public static void findString(String string) {
    boolean isFound = false;
    String allChars = "abcdefghijklmnopqrstuvwxyz ";
    char[] sequence = allChars.toCharArray();
    int lengthOfExpression = 3;
    //builder contains 3 whitespaces at the beginning
    StringBuilder builder = new StringBuilder("   ");

    int[] pos = new int[lengthOfExpression];
    int total = (int) Math.pow(allChars.length(), lengthOfExpression);
    for (int i = 0; i < total; i++) {
        for (int x = 0; x < lengthOfExpression; x++) {
            if (pos[x] == sequence.length) {
                pos[x] = 0;
                if (x + 1 < lengthOfExpression) {
                    pos[x + 1]++;
                }
            }
            builder.setCharAt(x, sequence[pos[x]]);
        }
        pos[0]++;

        if (builder.toString() == string) {
            isFound = true;
        }

        System.out.println(builder.toString());
    }
    System.out.println(isFound);
}

Expected result would be a 'true' printed at the end. Instead, my result is as follows:

//lots of lines of combinations omitted

r
s
t
u
v
w
x
y
z

false

Mangos
  • 147
  • 1
  • 7
  • What does the two character and the three character output look like? Someone can probably help faster with some more sample output. – ManLaw Jul 26 '19 at 11:38
  • Have you tried debugging yet? – MrSmith42 Jul 26 '19 at 11:38
  • 2 character sample: xy yy zy y az bz cz dz ez fz 3 character sample yrh zrh rh ash bsh csh dsh esh fsh gsh hsh also, the 1 and 2 character results have whitespaces behind them, so all the results are 3 char long. – Mangos Jul 26 '19 at 11:41

1 Answers1

0

Do not compare strings with ==, use .equals() instead; so for your code:

Change the if (builder.toString() == string) to if (builder.toString().equals(string))

Ra.cavalieri
  • 143
  • 2
  • 11