문제

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);
        }

    }


}
도움이 되었습니까?

해결책

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);
        }
    }
}

다른 팁

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");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top