First Approach
Second Approachpackage 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); } }
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); } }









