Searching for specific character in string with st

2019-09-04 16:54发布

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);
}
}

7条回答
Summer. ? 凉城
2楼-- · 2019-09-04 17:58
private static boolean hasAnyB(String str) {
   return str.contains("B") || str.contains("b");
}
查看更多
登录 后发表回答