*6.20 (Count the letters in a string) Write a method that counts the number of letters in
a string using the following header:
public static int countLetters(String s)
Write a test program that prompts the user to enter a string and displays the num-
ber of letters in the string.
import java.util.Scanner; public class ProgrammingExercise6_20 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String s = input.nextLine(); System.out.println("The number of letters is " + countLetters(s)); } public static int countLetters(String s) { int countLetter = 0; for (int i = 0; i < s.length(); i++) { if (isLetter(s.charAt(i))) { countLetter++; } } return countLetter; } public static boolean isLetter(char ch) { return ((ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A')); } }
you really helped me, thanks
ReplyDelete