有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。扫描器如何在Java中计算字符串中指定字符的实例?

我在这里找到了所有相关的东西,但由于某种原因,没有任何帮助。每当我运行此操作时,结果总是为0。不,我不能使用其他库来实现这一点(我看到了一些非常棒的解决方案,它们只包含一行内容,但我做不到)

public void process()
{
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your String:");
    String in_string = input.nextLine();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Press 1 to count the occurrence of a particular letter.");
    System.out.println("Press 2 to count the total words in your input sentance.");
    System.out.println("Press 3 to change your input sentance.");
    System.out.println("Press 4 to exit.");

    int option = input2.nextInt();

    if (option==1)
    {
        System.out.println("Choose your letter: ");
        String in_occurence = input.nextLine();


        for(int i = 0 ; i < in_string.length(); i++)
        {
            if(in_occurence.equals(in_string.charAt(i)))
            {
                charCount++;
            }
        }
        System.out.println(charCount);
    }

共 (2) 个答案

  1. # 1 楼答案

    您正在使用String#equals()Stringchar进行比较。那将永远给你false

    例如:

    System.out.println("a".equals('a'));  // false
    

    在比较之前,应通过获取索引0处的字符,将String转换为char

    if(in_occurence.charAt(0) == in_string.charAt(i))
    

    或者,只需将in_occurrence声明为char类型:

    char in_occurence = input.nextLine().charAt(0);
    
  2. # 2 楼答案

    您正在将一个String与一个char进行比较,即使字符串包含该字符,它也永远不相等

    你想要的是

    if (in_occurance.charAt(0) == in_string.charAt(i)) // compare char