0

I can't find a reason as to why arr[i].charAt(word) is not working.

public static void main(String[] args) {
    String [] arr = {"121", "333", "333"};
    int count = 0;
    int word = 0;
    for (int i = 0; i < arr.length; i++) {
        for (word = 0; word<arr[i].length(); word++) {
            if (arr[i].charAt(word) == 1) { //this line gives me trouble
                count++;
                System.out.println(count);
            }
        }
    }
}

Why isnt it?

2 Answers 2

6

charAt returns a char, so you need to put 1 in single quotes when comparing it as a char like so:

if(arr[i].charAt(word)== '1')
Sign up to request clarification or add additional context in comments.

Comments

1

You're not comparing a char to a char, you're comparing a char to an int. Which just happens to be legal because chars are numbers internally (put very simply, there's more to it than that of course).

Change the line to:

if(arr[i].charAt(word)== '1')

Notice the quotes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.