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);
}
}
Thank you so much Rahul..
ReplyDeleteSharing is caring and that's why whatever I learned I used to share.
The scanner is supportive things these days. We will easily scan any questions through this scanner. By filtering, we will check the question that we need to check. Too checking framework making our life less demanding. Quality 3d laser scanner Vancouver, BC
ReplyDelete