In: Computer Science
How to write Method in Java: public static in firstLetterFreq(char letter, String[] words]
{
// it returns 0 if (words == null OR words.length == 0)
// returns number of times letter is the first letter of a String in words array
// use equalIgnoreCase to check if letter and str.charAt(0) are equal and ignoring case
}
Explanation:I have written the method firstLetterFreq() and have also provided a demo code with main method to show the output of the program, please find the image attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//method
public static int firstLetterFreq(char letter, String[]
words)
{
int frequency = 0;
if (words == null || words.length
== 0)
return 0;
for (int i = 0; i <
words.length; i++)
{
if
(String.valueOf(words[i].charAt(0)).equalsIgnoreCase(String.valueOf(letter)))
{
frequency++;
}
}
return frequency;
}
//Demo code with main method
public class LetterFrequency
{
public static int firstLetterFreq(char letter,
String[] words)
{
int frequency = 0;
if (words == null || words.length
== 0)
return 0;
for (int i = 0; i <
words.length; i++)
{
if
(String.valueOf(words[i].charAt(0)).equalsIgnoreCase(String.valueOf(letter)))
{
frequency++;
}
}
return frequency;
}
public static void main(String[] args)
{
String words[] =
{ "hello", "hi", "How", "Are",
"You", "Hannah" };
char letter = 'h';
int frequency =
firstLetterFreq(letter, words);
System.out.println("The frequency
of letter " + letter + " ignoring the case is: " + frequency);
}
}
Output: