0

Give a two-dimensional array T with base type String and some string str (which can be treated like an array of type String) I want to check if T contains certain parts str as its entries. I tried this:

int indeksck = str.indexOf("C");

while(k<T.length){
    if(T[k][2] == str.substring(indeksck+1)){
        if(T[k][1] == str.substring(6, indeksck)){
            int ile_o = Integer.parseInt(T[k][0]);
            T[k][0]= Integer.toString(ile_o+1);
            T[k][3] = T[k][3]+"X"+str.substring(1,6);
            k = T.length+1;
        } else {
            k++;
        }

    } else {
        k++;

        if(k==T.length){
            k = 0;
            while(k<T.length){
                if(T[k][0]==null){
                    T[k][0] = Integer.toString(1);
                    T[k][1] = str.substring(6,indeksck);
                    T[k][2] = str.substring(indeksck+1);
                    T[k][3] = str.substring(1,6);
                    k = T.length+1;
                } else {
                    k++;
                }
            }
        }
    }
}

The problem is that the first part of my code is being ignored (even when condition should be satisfied). I would appreciate and suggestions on solving this problem.

davioooh
  • 23,742
  • 39
  • 159
  • 250
borg
  • 243
  • 2
  • 8
  • 8
    never compare strings with `==`, use `.equals()`, [read this](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) for an explanation. – jlordo Dec 29 '12 at 14:26
  • There's a lot going on here that you aren't explaining. Why start at substring index `6`? Why does every entry `T[k]` only have indices `0-3`? What's the `X` about? Why are you incrementing `T[k][0]` by 1 and converting back to string? Can you provide an example of the contents of `T` and `str`, and what exactly your code is looking for? – mellamokb Dec 29 '12 at 14:27
  • @jlordo I've tried this but it's didn't work. – borg Dec 29 '12 at 14:29
  • 1
    @mellamokb The string is formatted is special way, I don't think it's important. – borg Dec 29 '12 at 14:29
  • if `equals()` returns `false` for two strings, than they don't have the same exact content. – jlordo Dec 29 '12 at 14:30
  • It appears you are using arrays when you should be using objects (or a collection of objects) – Peter Lawrey Dec 29 '12 at 14:33
  • @PeterLawrey Do you mean I should use Object[][] instead of String[][]? – borg Dec 29 '12 at 14:34
  • I mean you should use `List` where MyType has fields with approriate types. This would make the purpose of each "column" clear and remove the need to convert between `int` and `String` – Peter Lawrey Dec 29 '12 at 14:37

2 Answers2

6

You cannot use == to do string compare. Try:

if(T[k][2].equals(str.substring(indeksck+1))) {
TieDad
  • 9,143
  • 5
  • 32
  • 58
2

== operator in Java is used for reference comparison. To check equivalence for objects (so also for strings) you need to use equals() method.

davioooh
  • 23,742
  • 39
  • 159
  • 250