Java Program 4: Extract Numbers From String and Add

Write a JAVA program for below requirements:

  1. Take an alphanumeric string from user.
  2. Verify if it is alphanumeric.
  3. If it is alphanumeric, extract all numbers present in string.
  4. Add all numbers and print it.

JAVA Program:

import java.util.Scanner;

import org.apache.commons.lang3.StringUtils;

public class ExtractNumbersFromString {

 public static void main(String[] args) {
 int sum=0;
 // Reading input from user
 Scanner sc= new Scanner(;
 System.out.println("Please enter the alphanumeric string:");
 String inputByUser= sc.nextLine();
 System.out.println("String entered by user: "+inputByUser);
 // Check if input string is alphanumeric Using regex
 boolean flagRegex= inputByUser.matches("([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*");
 // if string is alphanumeric, extract char and check if it is digit
 if(flagRegex == true)
 for(int i=0;i<inputByUser.length();i++)
 char c= inputByUser.charAt(i);
 sum=sum+ Character.getNumericValue(c);
 System.out.println("Sum of numbers found in "+inputByUser +" :"+sum);
 System.out.println(inputByUser+" is not an alphanumeric.");

Please enter the alphanumeric string:
String entered by user: hfghfgh54545
Sum of numbers found in hfghfgh54545 :23

Please enter the alphanumeric string:
String entered by user: %^&%dhfjf78
%^&%dhfjf78 is not an alphanumeric.


Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning