Java program to add all numbers present in AlphaNumeric String


First Approach
package com.nt.logical; import java.util.Scanner; public class AddNoFromString { public static void main(String[] args) { //getting the dynamic values from keyboard Scanner sc=new Scanner(System.in); System.out.println("Enter the String with number: "); String str=sc.nextLine(); //logic for removing the alpha characters String[] s=str.split("[A-Za-z]"); String ss=""; //logic to remove white spaces for(int i=0;i<s.length;i++) { ss=ss+String.valueOf(s[i]); } //getting number from ss obj int num=Integer.valueOf(ss); int sum=0; //logic to add the numbers while(num>0) { sum=sum+num%10; num=num/10; } //printing the value after adding System.out.println("Value :"+sum); } }
Second Approach
package com.nt.logical; import java.util.Scanner; public class AddNoFromString { public static void main(String[] args) { //getting the dynamic values from keyboard Scanner sc=new Scanner(System.in); System.out.println("Enter the String with number: "); String str=sc.nextLine(); //logic for removing the characters String[] s=str.split("[A-Za-z]"); int sum=0;
//logic to add the numbers for(int i=0;i<s.length;i++) { if(!(sArr[i].equals("")||(sArr[i].isBlank()))) { sum=sum+Integer.parseInt(s[i]); } } //printing the value after adding System.out.println("Value :"+sum); } }
Share:

Quote of the day

Popular Posts

Featured Post

Collection Framework Overview

Collection:- A collection (sometimes called a container) is simply an object that groups multiple elements into single unit. Collect...

Youtube Page

Facebook Page

Recent Posts

About

I am Shivaji Chandra and I'm a Computer Science Engineer. I love to write poems, jokes and quotes. click here →