Home > Software design >  Nested for loops to compare char arrays
Nested for loops to compare char arrays

Time:10-17

I am trying to compare the char Array c with s, in order to find out if c does not contain any element of s at index i. Therefore I am incrementing i and k at the same time, but it does not work for me.

The code should check if the entered number belongs to the decimal system (for example: 70, and 12B). For 70 it should be checked if at index zero and one (char[] c) the chars lie within the char array s. For 12B, index zero, one and two would be checked in char array s, only to find out that char array s does not contain index two ("B"). I hope I could make it a bit more clear.

public static boolean isDecimal(String number) {
    boolean t = true;
    char[] s = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    char[] c = number.toCharArray();

    for (int i = 0; i < number.length(); i  ) {
        for (int k = 0; k < 9; k  ) {
            if (c[i] != s[k]) {
                t = false;
            }
        }
    }

    return t;
}

CodePudding user response:

First of all, there are better ways to check whether a given String consists of digits, only. But let's 'debug' your code.

In pseudo code you're trying to do the following:

public static boolean isDecimal(String number) {
    char[] s = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    char[] c = number.toCharArray();

    boolean t = true;
    for (int i = 0; t && i < number.length(); i  ) {
        t = s contains c[i]
    }

    return t;
}

The problem is, that your inner loop doesn't test if s contains c[i], but if there's at least one digit that is different from c[i] (which always evaluates to true, of course).

Another (minor) problem is, that you don't test all elements of s, because of the condition k < 9 in your inner loop.

How to fix this? Basically, you've got to invert the logic:

boolean found = false;
for (int k = 0; !found && k < s.length; k  ) { // note the correct condition
    found = (c[i] == s[k]);
}

Having this, found == true if (and only if) s contains c[i]. Next, you can tell for sure that if found == false, number contains non-digits.

Let's put all together:

public static boolean isDecimal(String number) {
    char[] s = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    char[] c = number.toCharArray();

    for (int i = 0; i < number.length(); i  ) {
        boolean found = false;
        for (int k = 0; !found && k < s.length; k  ) {
            found = (c[i] == s[k]);
        }
        if (!found) return false;
    }

    return true;
}

Needless to say, that there are better options to perform this check, but I guess this is just code to learn something.

  • Related