How to calculate sum of all numbers in a string in java

How to calculate sum of all numbers in a string in java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package logic;
 
import java.util.Scanner;
 
public class Stringsum {
 
 
	public static void main(String[] args)
	{
		Scanner c=new Scanner(System.in);
		System.out.println("enter a string");
		String str=c.nextLine();
		char a[]=new char[str.length()];
		int i;
 
		int sum=0;
		for(i=0;i<=str.length()-1;i++)
		{
		if(str.charAt(i)>48 && str.charAt(i)<58)
		 {
 
	     	System.out.println(str.charAt(i)-48);
	     	System.out.println('a');
	    	sum=sum+str.charAt(i)-48;
 
	      }
 
	   }
 
		System.out.println("sum of number  "+ sum); 
	}
 
}

output:

1
2
3
4
5
6
7
8
9
10
11
enter a string
bhavesh1234
1
a
2
a
3
a
4
a
sum of number  10

Leave a Reply

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