WeekzGod
WeekzGod

Reputation: 333

Using .indexOf() in an if statement in java

I need to use an indexof method but terminal is telling me that it needs a variable but it gets a value. Can you guys explain how I fix this?

This is what I came up with by myself.

char a = 'a';
    if (s.indexOf(a, s.length()) == 61)
        System.out.println(" Your string contains the letter 'a' at index position: " + s.indexOf(97));
    else
        System.out.println(" Your string does not contain the letter 'a'");

Upvotes: 0

Views: 10210

Answers (1)

Pham Trung
Pham Trung

Reputation: 11284

If you are using Java. Method indexOf return the first position in string s that contains the string you pass in the method. It returns -1 if the string is not found.

if (s.indexOf("a") >= 0)
        System.out.println(" Your string contains the letter 'a' at index position: " + s.indexOf("a"));
    else
        System.out.println(" Your string does not contain the letter 'a'");

Upvotes: 2

Related Questions