【问题标题】:Counting the Occurrences of a User Specified Character in a String [duplicate]计算字符串中用户指定字符的出现次数[重复]
【发布时间】:2014-03-20 06:04:04
【问题描述】:

我的程序应该计算用户输入的字符在字符串中出现的次数。出于某种原因,我的程序没有执行 for 循环。在它打印出“输入要搜索的字符串:”之后,它不允许我输入字符串并打印出:“在'(输入的字符串)'中有 0 次出现'(输入的字符)'。”在新线上。我需要它能够在作为字符串输入的任何给定数量的单词中找到该字符的出现。我该怎么做才能使其正常运行?谢谢。

import java.util.Scanner;

public class CountCharacters {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter a character for which to search: ");
        char ch = input.next().charAt(0);

        System.out.println("Enter the string to search: ");
        String str = input.nextLine();

        int counter = 0;

        for (int i = 0; i < str.length(); i++) {
            if (ch == str.charAt(i)) {
                counter++;

            }

        }
        System.out.printf("There are %d occurrences of '%s' in '%s'.", counter, ch, str);
        System.out.println();

    }

}

【问题讨论】:

  • 另外,如果你有一个字符列表,你可以使用 Collections.frequency();一条线来完成你的工作:)
  • @devnull:谢谢,这应该会有所帮助。
  • @WhoAmI:我得试试看!

标签: java string for-loop character


【解决方案1】:

发生的情况是next() 方法不使用按Enter 时输入的换行符。由于该字符仍在等待读取,nextLine() 会消耗它。要解决此问题,您可以在 next() 调用之后添加 nextLine()

char ch = input.next().charAt(0);
input.nextLine(); // consumes new-line character

// ...

有关更多信息,您可以阅读此post

【讨论】:

  • 很好的解释。谢谢!
【解决方案2】:

在输入你的号码后,我猜你正在按&lt;enter&gt;,所以在输入你的字符串之前需要仔细阅读

试试

char ch = input.next().charAt(0);
input.nextLine();
System.out.println("Enter the string to search: ");
String str = input.nextLine();

【讨论】:

    猜你喜欢
    • 2012-05-31
    • 2011-03-02
    • 2020-06-14
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多