问题
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.
- Either have the user enter a char, or take the first character from
the string they entered using
character.chatAt(0). - Use
word.lengthto figure out how long the string is 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