Search code examples
javacountletter

Count letter in a word from scanner, java


My code is looking like this right now, it's counting the letters in the word but I would like my code to count every letter in the word so if I write banana or nine, the code will ask which letter to count, and if I choose "N", it will print 2 "N". Please help me out.

    System.out.println("Ange ordet du vill leta i: ");
    String str1 = sc.nextLine();

    System.out.println("Ange bokstaven du vill leta efter: ");
    String str2 = sc.nextLine();

    int count = 0;

    for(int i = 0; i < str2.length(); i++) {
        if(str2.charAt(i) != ' ')
            count++;
    }

    System.out.println("Antal bokstäver i ditt ord: " + count);

Solution

  • You don't need to count every letter at first. You should count after getting the letter to count. But depending on the scenario. I assume that you need to get the count of the letter in a particular string.

    You can wrap counting logic inside a while() to do this over and over again.

    import java.util.Scanner;
    
    public class MyClass {
        public static void main(String args[]) {
        
          Scanner scanner = new Scanner(System.in);
            
          System.out.println("enter word");    
          String s = scanner.next();
          
          System.out.println("enter letter");
              
          char a = scanner.next().charAt(0);
          
          int count = 0;
          
          for(int i = 0; i < s.length(); i++){
              if(s.charAt(i) == a){
                  count++;
              }
          }
          
          System.out.println(count);
          
        }
    }