Count the occurrences of a letter in a string

前端 未结 10 1541
礼貌的吻别
礼貌的吻别 2021-01-21 03:42

I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This

10条回答
  •  佛祖请我去吃肉
    2021-01-21 03:50

    Try this

    forget String letter = "" <-- Delete
    forget letter = in.next() <-- Delete

        // There's no nextChar() method, so this is a work aroung
        char ch = in.findWithinHorizon(".", 0).charAt(0);
    
        int letter = 0;
        for (int i = 0; i < sentence.length(); i++) {
    
            if (sentence.charAt(i) == ch) {
                letter++;
            }
        }
    
        System.out.println(letter);  // print number of times letter appears
    
        // You don't want this
        System.out.print(sentence.charAt(letter)); // Makes no sense
    

提交回复
热议问题