In: Computer Science
Create a method called firstLetter that takes a String parameter and integer parameter. It should return -1 if the number of words in the given String is greater than or equal to the integer parameter (it should return -1 and not process the String any further) (4 points). If the String does not have more words than the given integer, the method should return 1 if all the words in the string start with the same letter(8 points) and 0 if all the words do not start with the letter(4 points). (4 points: correct method signature-2 for parameter, 2 for return type) For example, System.out.println(firstLetter("Charlie chews chewy chews.",10)); would print to screen 1 since all words start with the same letter (notice the method is not case sensitive) and the number of words is less than 10.
code in java
Method code
public static int firstLetter(String str, int n)
{
String words[]=str.split(" ");
if(words.length>=n)
return -1;
for(int i=0;i<words.length-1;i++)
if(Character.toUpperCase(words[i].charAt(0))!=Character.toUpperCase(words[i+1].charAt(0)))
return 0;
return 1;
}
for testing i created this simple program
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println("firstLetter(\"Charlie chews chewy
chews.\",10))="+firstLetter("Charlie chews chewy
chews.",10));
System.out.println("\nfirstLetter(\"Charlie chews chewy
chews.\",3))="+firstLetter("Charlie chews chewy chews.",3));
System.out.println("\nfirstLetter(\"Charlie chews jay
chews.\",10))="+firstLetter("Charlie chews jay chews.",10));
}
public static int firstLetter(String str, int n)
{
String words[]=str.split(" ");
if(words.length>=n)
return -1;
for(int i=0;i<words.length-1;i++)
if(Character.toUpperCase(words[i].charAt(0))!=Character.toUpperCase(words[i+1].charAt(0)))
return 0;
return 1;
}
}
output
If you have any query regarding the code please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.