0

第一个问题在这里。已经做了一些研究,但没有运气。我认为我的代码中几乎所有内容都正确,但我无法让它工作。它需要从用户也输入的字符串或短语中读取单个字符,然后打印出找到它的次数。我是java初学者,非常感谢任何帮助!谢谢。

import java.util.Scanner;

public class CountCharacters{
    public static void main(String[] args) {
            Scanner input = new Scanner(System.in);

            int timesFound;
            String stringSearched, characterSearched;

            System.out.printf("Enter a character for which to search: ");
            characterSearched = input.next();       
            System.out.printf("Enter the string to search: \n");
            stringSearched = input.nextLine();


            int numberOfCharacters = stringSearched.length();
            timesFound = 0;



            for (int x = 0; x < numberOfCharacters; x++)
            {
                char charSearched = characterSearched.charAt(0);

                if ( charSearched == stringSearched.charAt(x))
                    timesFound++;

                System.out.printf("\nThere are %d occurrences of \'%s\' in \"%s\"",
                        timesFound, characterSearched, stringSearched);
            }

   }    
}   
4

2 回答 2

0

请在您的代码中注释掉这一行:

// stringSearched = input.nextLine();

并替换为以下 2 行。

input.nextLine();
stringSearched = input.next();

nextLine()将位置设置为下一行的开头。所以你需要另一个input.next().

这是我在这个论坛上的第一个答案。所以请原谅我可能犯的任何礼仪错误。

于 2013-10-25T03:55:45.173 回答
0

看看for循环。它在做你想做的事吗?我觉得里面的代码太多了。这是我将如何完成你的任务

  • 读取两次System.in并将输入characterSearched分别分配给stringSearched
  • 像你一样初始化一个计数器timesFound

    int timesFound = 0;
    
  • 获取第一个字符characterSearched

    char charSearched = characterSearched.charAt(0);
    
  • 循环遍历字符串stringSearched并计数

     for (int x = 0; x < stringSearched.length(); x++){
            if (charSearched == stringSearched.charAt(x))
                timesFound++;
        }
    
  • 打印结果

    System.out.printf("\nThere are %d occurrences of \'%s\' in \"%s\"",
                    timesFound, characterSearched, stringSearched);
    
于 2013-10-25T03:39:09.713 回答