I need help with my class assignment. I am supposed to write a java program to count the number of digits in a string using: public static int countDigits(String s) can anyone help...I cant seem to figure it out from what I have

public class Ex8_5 {
  public static void main(String[] args) {
    
    java.util.Scanner input = new java.util.Scanner(System.in);
    System.out.print("Enter a string: ");
    String s = input.nextLine();
    
    System.out.println("The number of digits is " + countDigit(s));
  }
  public static int countDigits(String s) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
    if (Character.isLetter(s.charAt(i))) {
    count++;
      }
    }
    return count;
  }
}

You are calling System.out.println("The number of digits is " + countDigit(s)); but your method name is public static int countDigits(String s)

Secondly the code in this case is counting number of letters instead of numbers. you need to correct the logic there.

You are calling System.out.println("The number of digits is " + countDigit(s)); but your method name is public static int countDigits(String s)

Secondly the code in this case is counting number of letters instead of numbers. you need to correct the logic there.

OK, how would I do this

try this code.comparing chars with ascii values

String str="abcd2efg345646";
 char ch[]=str.toCharArray();
  int length=str.length(),count=0;
  for(int i=0;i<length;i++)
  {
 int x=ch[i];
 if(x>=48 && x<=57)
 count++;
 }
return count;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.