In Java language write a program that contains the following 3 methods 1.public
ID: 3780241 • Letter: I
Question
In Java language write a program that contains the following 3 methods
1.public static int howMany (char c, String s);
Return the number of times the char c appears in the String s
2.public static String initials(String s)
Assume without checking that s consists of one or more English words, separated by single spaces, no space at the beginning or end,e.g.
"Just a variable assignment".Return the String formed by taking the first letter from each word, e.g."Java".
3.public static middle (String []a)
Assume without checking that each element of array a consists of a word with an odd number of letters. Return the word formed by taking the middle letter of each word. For example, if a contained {"The", "big", "brown", "elephants"}, then the method would return "hioh".
The program should also contain a main method that calls each of these 3 methods, and attach a sample run.
Explanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
public class StringOperations {
public static int howMany (char c, String s){
int count = 0;
for(int i=0; i<s.length(); i++)
if(c == s.charAt(i))
count++;
return count;
}
public static String initials(String s) {
String res = "";
char prev = ' ';
for(int i=0; i<s.length(); i++){
if(prev == ' ')
res = res + s.charAt(i);
prev = s.charAt(i);
}
return res;
}
public static String middle (String []a){
String res = "";
for(int i=0; i<a.length; i++){
int mid = a[i].length()/2;
res = res + a[i].charAt(mid);
}
return res;
}
public static void main(String[] args) {
System.out.println(" 'a' count: "+howMany('a', "edfkneawkdafkdaad"));
String s = "Just a variable assignment";
System.out.println(initials(s));
String[] a= {"The", "big", "brown", "elephants"};
System.out.println(middle(a));
}
}
/*
Sample run:
'a' count: 4
Java
hioh
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.