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

Java program reverse number

Write a Java program reverse number

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
package logic;
import java.util.Scanner;
 
public class Reversenumber 
{
 
 
   public static void main(String[] args) 
      {
 
        Scanner scn=new Scanner(System.in);
        System.out.println("enter number");
 
	int n=scn.nextInt();
 
	int digit=0;
	int reverse=0;
 
	while(n!=0)
	 {
 
           digit=n%10;
 
	   n=n/10;
	   reverse=reverse*10+digit;
 
	 }
 
	   System.out.println(reverse);
 
	}
}

output:

1
2
3
enter number
1234
4321