2013-10-25 30 views
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); 
      } 

    }  
} 
+1

什么不起作用? –

+0

看起来不错。将打印输出移出循环 – iluxa

回答

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); 
    
0

请注释掉这行代码:

// stringSearched = input.nextLine(); 

,代之以以下2行。

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

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

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

相关问题