narcisse
narcisse

Reputation: 451

Loop that doesn't end

Here is a piece from my code. My problem is that this line System.out.println(digit.contains(0)); prints false even when there is a zero in the list "digit".

    int x = 5;
    int y = 0;
    int z;
    ArrayList<Character> digit = new ArrayList<>();
    char[] new_digit = {};
    boolean end_loop = true;

    do {
        z = x * y;
        new_digit = ("" + z).toCharArray();
        for (int k = 0; k < new_digit.length; k++) {
            if (!digit.contains(new_digit[k])) {
                digit.add(new_digit[k]);
            }
        }
        System.out.println(digit.contains(0));

what is the problem exactly?

Upvotes: 0

Views: 130

Answers (1)

Michael
Michael

Reputation: 44160

The list is a list of characters:

ArrayList<Character> digit = new ArrayList<>();

You are checking whether it contains the integer zero:

digit.contains(0)

Because this is an integer and not a character, it will will be implicitly converted to the ASCII character represented by that number, which is NULL. The character 0 is represented in ASCII by the integer 48.

If you want to check whether your list contains the character zero, do this:

digit.contains('0')

Upvotes: 1

Related Questions