226k views
0 votes
Write the function tCount that counts how many times the letter t (either lowercase or uppercase) occurs in a string. It takes a string s as input and returns an integer, the number of characters in the string that are t or T. Please use a for loop to do the computation. I am banning the built-in function count for obvious reasons. It is good to understand how these basic functions are built. You could test the quality of your code using count before you submit, but be sure to remove those test calls when submitting! Fun fact: bad encryption algorithms may be broken using letter frequencies. Word frequencies are an interesting way to analyze the provenance of a piece of text (is it likely that Shakespeare wrote this

1 Answer

2 votes

Answer:

import java.util.Scanner;

public class CountT {

public static void main(String[] args) {

Scanner in = new Scanner (System.in);

System.out.println("Enter a word");

String word = in.nextLine();

//convert to all lower case

String str = word.toLowerCase();

int tcount = 0;

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

if(str.charAt(i)=='t'){

tcount++;

}

}

System.out.println("Total number of ts: "+tcount);

}

}

Explanation:s

  • Import Scanner class
  • Prompt user for input
  • Store in a variable
  • Convert user's input into all lower cases
  • Create a variable tcount and initilize to zero
  • Using a for loop, iterate through the entire length of the string and increment tcount by 1 each time the character t is found
  • Output tcount

User Ashweta
by
4.7k points