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

时间:2013-10-25 03:08:14

标签: java input console

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

答案 0 :(得分: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);
    

答案 1 :(得分:0)

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

// stringSearched = input.nextLine();

并替换为以下两行。

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

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

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