字符串

时间:2016-10-04 22:38:41

标签: java string character

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

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

}

}

2 个答案:

答案 0 :(得分:1)

以下是从this之前提出的问题中获取的解决方案,并进行了编辑以更好地适应您的情况。

  1. 让用户输入一个字符,或者从中获取第一个字符 他们使用word.length输入的字符串。
  2. 使用word.charAt()计算字符串的持续时间
  3. 创建一个for循环并使用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); 来计算角色出现的次数。

    {{1}}

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