简体   繁体   English

计算来自扫描仪的单词中的字母,java

[英]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".我的代码现在看起来像这样,它正在计算单词中的字母,但我希望我的代码计算单词中的每个字母,所以如果我写banananine ,代码会询问要计算哪个字母,如果我选择“N”,它将打印 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);

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.您可以将计数逻辑包装在 while() 中以一遍又一遍地执行此操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM