Question

I'm trying to make a program that whenever a character (for examine 'a') is found it prints it and the move on to next character to check. Keeps doing it until the end of the word.length. It is what I have done so far but does not work,

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = in.next();
    String a = "a";
    int i;
    char found = 0;
    char F;

    for (i = 0; i < word.length(); i++)
    {
        F = word.charAt(i);

        if (F == found)
        {
            System.out.println(i);
        }

    }


}
Était-ce utile?

La solution

Try this

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = in.next();        
    char F;

    for (int i = 0; i < word.length(); i++) {
        F = word.charAt(i);
        if (F == 'a') {
            System.out.println(i);
        }
    }
}

Autres conseils

Try with

       Scanner in = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = in.next();
        Pattern p=Pattern.compile("a");
        Matcher matcher=p.matcher(word);
        boolean b=false;
        while(b=matcher.find())
        {
            System.out.println(matcher.start()+"");
        }

Edit:

Pattern.compile("a");

Compiles the given regular expression into a pattern

p.matcher(word);

Creates a matcher that will match the given input against this pattern. 

If you would like to search for source string like aba then for all occurrence of expression a, it will do like

source:aba
index:012

we can see two occurences of the expression a: one start from position 0 and second starting from 2. so the output is 0 2

use this one simple

 string.indexOf("a");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top