Frequently Asked Java Program 04: Java Program to Extract Numbers From String and Add

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to extract numbers from a string.

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.in);
  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);
    if (Character.isDigit(c))
     sum = sum + Character.getNumericValue(c);

   }
   System.out.println("Sum of numbers found in " + inputByUser + " :" + sum);
  } else {
   System.out.println(inputByUser + " is not an alphanumeric.");
  }




 }
}

Output:

[java] Please enter the alphanumeric string: hfghfgh54545 String entered by user: hfghfgh54545 Sum of numbers found in hfghfgh54545 :23 ================================================================== Please enter the alphanumeric string: %^&%dhfjf78 String entered by user: %^&%dhfjf78 %^&%dhfjf78 is not an alphanumeric.

[/java]