java characters in a string

我的未来我决定 提交于 2019-12-13 09:48:32

问题


so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.

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

}

}

回答1:


This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).

@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"));



回答2:


Here is a solution taken from this previously asked question and edited to better fit your situation.

  1. Either have the user enter a char, or take the first character from the string they entered using character.chatAt(0).
  2. Use word.length to figure out how long the string is
  3. Create a for loop and use word.charAt() to count how many times your character appears.

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


来源:https://stackoverflow.com/questions/39862838/java-characters-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!