Write a program that accepts an input string from the user, and determines how m
ID: 3768241 • Letter: W
Question
Write a program that accepts an input string from the user, and determines
how many times a user-specified character appears within the string. (Hint:
Look up the 's' option of the input function using the MATLAB Help
Browser.)
Actually you have to get 2 things from the user:
The user-specified input string to search in
The user-specified character to search for (in order to count how many times it occurs)
If the user enters a string instead of a single character you should just use the first character of the string.
Example Run #1
Enter a string to search: Look for me please
Enter a character to look for: e
e was found 3 times in Look for me please
Example Run #2
Enter a string to search: This is another test
Enter a character to look for: stop
s was found 3 times in This is another test
Example Run #3
Enter a string to search: This is another test
Enter a character to look for: z
z was found 0 times in This is another test
Explanation / Answer
import java.util.Scanner; 02 03 public class LetterCounter 04 { 05 public static void main(String[] args) 06 { 07 String name; //String for user input 08 String upper; //Convert String to upper case 09 String upper2; //Convert Letter string to upper case 10 String letter; //Letter that the user enters 11 char charLetter; //Get the character in string 12 int i; //For counting number of characters in string 13 int count = 0; //For counting how many characters in string 14 15 //Create scanner object 16 Scanner keyboard = new Scanner(System.in); 17 18 //Get the users String input 19 System.out.println("Please enter any word"); 20 name = keyboard.nextLine(); 21 upper = name.toUpperCase(); 22 23 //Get the character to count 24 System.out.println("Please enter any letter in that word."); 25 letter = keyboard.nextLine(); 26 upper2 = letter.toUpperCase(); 27 charLetter = upper2.charAt(0); 28 29 //Controlled loop to count characters 30 for (i = 0; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.