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:
%^&amp;%dhfjf78
String entered by user: %^&amp;%dhfjf78
%^&amp;%dhfjf78 is not an alphanumeric.
[/java]

#HappyCoding

12 thoughts on “Frequently Asked Java Program 04: Java Program to Extract Numbers From String and Add

  1. Thanks for the share

    [a-zA-Z]+[0-9]+[A-Za-z0-9]* should be the regular expression to get an alphanumeric which actually has some numbers in it . If there is no number then it will return false

    boolean flagRegex = inputByUser.matches(“([A-Za-z]+[0-9]+[A-Za-z0-9]*”);

  2. I feel we also can do this without even using regex:
    package javapractice;
    import java.util.Scanner;

    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);

    for(int i=0;i<inputByUser.length();i++)
    {
    char c= inputByUser.charAt(i);
    if(Character.isDigit(c))
    sum=sum+ Character.getNumericValue(c);

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

    }
    }

    1. @Raji: This is wrong for Test data as Test00Test. Output should be zero but your code will print “is not an alphanumeric”.

  3. Thanks for the share

    2 things here

    FYI
    1) to use String.utils we need to have Apache lang library added in the project

    Below code is not correct
    2)boolean flagRegex= inputByUser.matches(“[a-zA-Z0-9]+”);

    if you have a string whcih just has alphabets like ‘udzialMeansShare’ , it will return true i.e. its an alphanumeric and else portion will never be executed
    you can make the below changes

    boolean flagRegex= inputByUser.matches(“[a-zA-Z]+”); // this will return true only if we have a string which does not have characters

    so we can do if ( !flagRegex)

    1. Actually I was trying to write regex to verify alphanumeric if string has alphabets and numbers both. StringUtils and regex are giving true if string contains only characters also. Main focus is to extract numbers as of now. I will update code once i writw proper regex.

  4. Hi Amod,

    I tried like below

    public class NumbersInString2 {
    public static void main(String[] args) {
    int count = 0;
    String s = “jisncansjkcna33wqsnfjks732hjsddh71”;
    String str[] = s.split(“[a-zA-Z]+”);
    for (int i = 1; i < str.length; i++) {
    count = count + Integer.parseInt(str[i]);
    }
    System.out.println(str[0]+" : "+count);

    }
    }

    Output

    : 836

    My question here is we are splitting given string by numbers and there are 3 numbers in it i.e, 33,732,71 so why str[0] is "" (Empty String). its working fine if start the loop using 1.

    1. That’s the way split method works.
      Code 1:
      String str1 [] = “amod123”.split(“m”);
      System.out.println(“Length: “+str1.length);
      for(int i=0;i

Leave a Reply to Gaurav Khurana Cancel reply

Your email address will not be published. Required fields are marked *