In: Computer Science
III. Answer part A,B, and C. (in JAVA)
3a)
Return the number of times the letter 'a' occurs in a String.
countA("abc") → 1
countA("wxyz") → 0
countA("bcaca") → 2
3b)
Return the number of times the given letter ch occurs in the given String str.
countNumChar("abc", "a") → 1
countNumChar("wxyz", "b") → 0
countNumChar("bcaca", "c") → 2
3c)
Count the number of characters that are either a or b in a String. Try to use only one for loop.
countAorB("abc") → 2
countAorB("xyz") → 0
countAorB("ab") → 2
public class Main{
// it counts number of a
public int countA(String s){
int i, count=0;
for(i=0;i<s.length();i++){
if(s.charAt(i)=='a')
count++;
}
return count;
}
// it counts number of a charater
public int countNumChar(String s, char x){
int i, count=0;
for(i=0;i<s.length();i++){
if(s.charAt(i)==x)
count++;
}
return count;
}
// it counts chracters either a or b
public int countAorB(String s){
int i, count=0;
for(i=0;i<s.length();i++){
if(s.charAt(i)=='a'|| s.charAt(i)=='b')
count++;
}
return count;
}
public static void main(String args[]){
// declare object of class
Main obj=new Main();
// call the functions and display the result
System.out.println("Number of `a' in "+"abc"+" is: "+obj.countA("abc"));
System.out.println("Number of `a' in "+"wxyz"+" is: "+obj.countA("wxyz"));
System.out.println("Number of `a' in "+"bcaca"+" is: "+obj.countA("bcaca")+"\n");
System.out.println("Number of `a' in "+"abc"+" is: "+obj.countNumChar("abc",'a'));
System.out.println("Number of `b' in "+"wxyz"+" is: "+obj.countNumChar("wxyz",'b'));
System.out.println("Number of `c' in "+"bcaca"+" is: "+obj.countNumChar("bcaca",'c')+"\n");
System.out.println("Number of `a' or `b' in "+"abc"+" is: "+obj.countAorB("abc"));
System.out.println("Number of `a' or `b' in "+"xyz"+" is: "+obj.countAorB("xyz"));
System.out.println("Number of `a' or `b' in "+"ab"+" is: "+obj.countAorB("ab"));
}
}
___________________________________________________________________
Number of `a' in abc is: 1
Number of `a' in wxyz is: 0
Number of `a' in bcaca is: 2
Number of `a' in abc is: 1
Number of `b' in wxyz is: 0
Number of `c' in bcaca is: 2
Number of `a' or `b' in abc is: 2
Number of `a' or `b' in xyz is: 0
Number of `a' or `b' in ab is: 2
___________________________________________________________________
Note: If you have
queries or confusion regarding this question, please leave a
comment. I would be happy to help you. If you find it to be useful,
please upvote.