-1

//The Prompt is: Write a program that asks the user to enter a string, and //then ask the user to enter a character. The program should count and display //the number of times that the specified character appears in the string.

import java.util.Scanner;
public class LetterCounter{
Scanner keyboard = new Scanner (System.in);     //Scanner
// Declare Variables
    String userString;      // String user entered
    String userCharacter;   // Character user entered
    int StringSize;      
// Ask the user to enter a string
    System.out.println("Please Enter a String.");
    userString = keyboard.nextLine();

// Ask the user to enter a charcter
    System.out.println("Please Enter a Character.");
    userCharacter = keyboard.nextLine();

// Count and display the number of times that character appears in the
// string chosen by the user.
    int character; 
    character = Integer.parseInt(userCharacter);
    StringSize = userString.charAt(character);
}
}

For some reason I can't get it to work, I just don't know where to go from here. Do I possibly need a FOR-LOOP?

Thanks for your help

Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34
Lori Ramirez
  • 1
  • 1
  • 1

2 Answers2

1

Hi have a look at this

package gmit;

import java.util.Scanner;
public class LetterCounter{

    public static void main(String[] args) {
        String keyBoardChar;    

Scanner keyboard = new Scanner (System.in);     //Scanner
// Declare Variables
    String userString;      // String user entered
    char userCharacter;   // Character user entered
    int StringSize;      
// Ask the user to enter a string
    System.out.println("Please enter a string");
    userString = keyboard.nextLine();

// Ask the user to enter a charcter

    System.out.println("Please Enter a Character.");
    char kChar = keyboard.next().charAt(0);

// Count and display the number of times that character appears in the
// string chosen by the user.
    int character = 0; 
    //character = Integer.parseInt(userCharacter);
    //StringSize = userString.charAt(character);

    char[] StringToChar = userString.toCharArray();
    for(int i = 0; i < StringToChar.length - 1; i++){
        if ( StringToChar[i] == kChar){
            character++;
        }
    }
    System.out.println("character count is " + character);

} }

I selected the letter using char kChar = keyboard.next().charAt(0);

and converted the String to a Char array, ran a for loop going through each letter and checking if it was the same as the selected character. Each time the check was true I added one to the character counter.

Rob Carrigan
  • 101
  • 1
  • 2
  • 9
0

Yes, you'll need to use a for loop.

int count = 0;
for (char ch: userString.toCharArray()) {
    if(userChar == ch) count++;
}
hermitmaster
  • 155
  • 1
  • 10