Count the occurrences of a letter in a string

前端 未结 10 1625
礼貌的吻别
礼貌的吻别 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 04:04

    I see a couple of issues. First you have two variables with the same name.

    Second your if condition check for the lenght of the sentence to be greater then 0 instead of checking for character equality.

    Scanner in = new Scanner(System.in);
    
    char inLetter = "";
    String sentence = "";
    System.out.println("Enter a character for which to search");
    inLetter = in.next().charAt(0);
    System.out.println("Enter the string to search");
    sentence = in.next();
    
    int letter = 0;
    for (int i = 0; i < sentence.length(); i++) {
        char ch = sentence.charAt(i);
        if (inLetter == ch) {
            letter++;
        }
    }
    
    System.out.print(sentence.charAt(letter));
    

    I would also strongly suggest to validate the input (which is not done in the example above) instead of just assuming you got 1 character from the first input and 1 sentence in the second.

提交回复
热议问题