Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. Ex: If the input is: n Monday the output is: n appears this many times: 1 Ex: If the input is: z Today is Monday the output is: z appears this many times: 0 Ex: If the input is: n It's a sunny day the output is: n appears this many times: 2 Case matters. Ex: If the input is: n Nobody the output is: n appears this many times: 0

Respuesta :

Answer:

import java.util.Scanner;

public class NumberOfOccurences {

public static void main(String[] args) {

 // Create an object of the Scanner class to allow for user inputs

 Scanner input = new Scanner(System.in);

 // Prompt user to enter text

 System.out.println("Please enter the phrase");

 // Store text in a variable

 String phrase = input.nextLine();

 // Prompt user to enter character to be checked

 System.out.println("Please enter the character to check");

 // Store character in a char variable

 char character = input.next().charAt(0);

 // Create and initialize a variable count to zero

 // count will hold the number of occurrences of the character in the phrase

 int count = 0;

 // Loop through each of the character in the string text

 // At every cycle of the loop, compare the character of the string

 // with the character to be checked.

 // If they match, count is incremented

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

  if (phrase.charAt(i) == character) {

   count++;

  }

 }

 // Print out the number of occurrences due to count

 System.out.println(character + " appears this many times " + count);

}

}

Explanation:

The source code file has been attached to this response and has been saved as "NumberOfOccurrences.java". Please download the file and go through the code including the comment. Pay attention to the comments for readability and understandability.

Hope this helps!

Ver imagen stigawithfun