191k views
2 votes
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string.

User Noughtmare
by
4.1k points

1 Answer

6 votes

Answer:

import java.util.Scanner;

public class ANot {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Please enter a word");

String word = in.next();

System.out.println("Please enter a character");

char ca = in.next().charAt(0);

int countVariable = 0;

for(int i=0; i<word.length(); i++){

if(ca ==word.charAt(i))

countVariable++;

}

System.out.println(countVariable);

}

}

Step-by-step explanation:

  1. Using the Scanner Class prompt and receive the users input (the word and character). Save in seperate variables
  2. create a counter variable and initialize to 0
  3. Use a for loop to iterate over the entire length of the string.
  4. Using an if statement check if the character is equal to any character in string (Note that character casing upper or lower is not handled) and increase the count variable by 1
  5. print out the count variable

User Amith Dissanayaka
by
4.6k points