Will Ricard Will Ricard - 1 year ago 99
Java Question

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



Answer Source

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

System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download