2016-10-04 52 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);