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);
}
}
Something like this:
static boolean check(String str){
if(str.indexOf('B')>0 || str.indexOf('b')>0 )
return true;
else
return false;
}
private static boolean hasAnyB(String str) {
return str.contains("B") || str.contains("b");
}
Use the built-in matches()
method, which uses regex:
private static boolean hasB(String str) {
return str.matches(".*[bB].*");
}
Using regex is a near way to handle mixed case issues.
Just Deploy all coding inside a static
method that's it
public static void main(String[] args)
{
methodOne("Pass string over here");
}
public static boolean methodOne(String s)
{
return s.contains("B");
}
To get the count of b
or B
you can do
int bCount = w.replaceAll("[^Bb]", "").length();
If you have to use a hasB method you could do it like this, though its pretty inefficient and longer than it needs to be
int count = 0;
for(String ch: w.split("")) // one character at a time.
if(hasB(ch))
count++;
private static boolean hasAnyB(String str) {
return str.toLowerCase().contains("b");
}
The easiest i could think.
static boolean isThisB(String s, int count) {
for(int i=0; i<s.lenght(); i++) {
char c = s.charAt(i);
if(c == 'b' || c == 'B')
count ++;
}
return count > 0;
}