Java bootcamp · Lab 41

Count digits

easyStrings8 minLesson: Strings

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a line; count digit characters.

Examples

Example 1
Input
ab12c3
Output
3
Hint
  1. Character.isDigit
Show correct code

Peek only after you have tried. You can still Check your own version.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String line = in.nextLine();
    int c = 0;
    for (int i = 0; i < line.length(); i++) if (Character.isDigit(line.charAt(i))) c++;
    System.out.println(c);
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.