I have to make a program that counts the number of the letter B in a string. I got that part already, but it also requires me to use a static method that returns true or false based on if the string has any Bs in it and i really don't see how to fit that part in.
import java.util.Scanner;
public class CountB {
// write the static method “isThisB” here
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a string: ");
String w = keyboard.nextLine();
int count=0;
for (int i=0; i<w.length(); i++)
{
if (w.charAt(i)=='B'||w.charAt(i)=='b')
{
count++;
}
}
System.out.println("Number of B and b: "+ count);
}
}
Use the built-in
matches()
method, which uses regex:Using regex is a near way to handle mixed case issues.
The easiest i could think.
To get the count of
b
orB
you can doIf you have to use a hasB method you could do it like this, though its pretty inefficient and longer than it needs to be
Just Deploy all coding inside a
static
method that's itSomething like this: