2016-10-04 34 views
-3

所以我的问题是我需要让用户输入一个string。那么他们会输入一个他们想要统计的角色。所以程序应该是count how many times the character他们输入的字符串会出现,这是我的问题。如果有人能给我一些关于如何做到这一点的信息,将不胜感激。字符串中的java字符

import java.util.Scanner; 
public class LetterCounter { 

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

    System.out.println("please enter a word");//get the word from the user 
    String word= keyboard.nextLine(); 
    System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string 
    String character= keyboard.nextLine(); 

} 

} 

回答

0

这应该这样做。它的功能是获取一个字符串来查看,获取一个字符,遍历字符串查找匹配项,计算匹配数量,然后返回信息。有更多优雅的方法来做到这一点(例如,使用正则表达式匹配器也可以)。

@SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); 

System.out.print("Enter a string:\t"); 
String word = scanner.nextLine(); 

System.out.print("Enter a character:\t"); 
String character = scanner.nextLine(); 

char charVar = 0; 
if (character.length() > 1) { 
    System.err.println("Please input only one character."); 
} else { 
    charVar = character.charAt(0); 
} 

int count = 0; 
for (char x : word.toCharArray()) { 
    if (x == charVar) { 
     count++; 
    } 
} 

System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times")); 
+0

真棒工作,我只是有一个问题,为什么是charVar = 0开始? –

+0

它需要被初始化,因为它是一个字符。所有的字符也是整数,所以0看起来像任何值一样好。 – ifly6

1

这里是this以前问的问题采取和编辑,以更好地适应您的情况的解决方案。

  1. 要么让用户输入一个字符,或采取的第一个字符从 他们使用character.chatAt(0)输入的字符串。
  2. 使用word.length找出串有多长
  3. for循环创建并使用word.charAt()算你的角色出现了多少次。

    System.out.println("please enter a word");//get the word from the user 
    String word= keyboard.nextLine(); 
    System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string 
    String character = keyboard.nextLine(); 
    char myChar = character.charAt(0); 
    
    int charCount = 0; 
    for (int i = 1; i < word.length();i++) 
    { 
        if (word.charAt(i) == myChar) 
        { 
         charCount++; 
        } 
    } 
    
    System.out.printf("It appears %d times",charCount);