Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

java characters in a string

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

}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...