有 Java 编程相关的问题?

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

java如何从用户输入的单词或短语中读取单个字符

这里的第一个问题。已经做了一些研究,但没有运气。我想我的代码中几乎所有内容都是正确的,但我无法让它工作。它需要从用户输入的字符串或短语中读取单个字符,然后打印出找到它的次数。我是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);
            }

   }    
}   

共 (2) 个答案

  1. # 1 楼答案

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

    // stringSearched = input.nextLine();
    

    并替换为以下两行

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

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

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

  2. # 2 楼答案

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

    • System.in读取两次,并将输入分别分配给characterSearchedstringSearched
    • 初始化计数器,就像使用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);