• Register
28,501 points
12 7 5

When we are learning programming, we come across many hands-on exercise problems given to us by our teachers. In this article, we are going to the solution to one of those exercises. 
In the solution, we will first hardcode the string and if it goes well, we will change the code to prompt the user to enter the string, and then the sum will be calculated. Let’s do it!


public class Main
{
	public static void main(String[] args) {
		int sum_of_numbers = string_num_sum("5um 0f num63r5 1n 7h3 5tr1ng");   //string
		System.out.println("Sum of numbers in the string: " + sum_of_numbers);  //result
	}
	public static int string_num_sum(String str)  //method that checks whether a character is digit and add it to the sum
	{
       int sum = 0;
        for(int i = 0; i < str.length() ; i++)   //looping through the string
        {
            if( Character.isDigit(str.charAt(i)) )  //checking if the character at certain position is digit or not
            {
                sum = sum + Character.getNumericValue(str.charAt(i));  //digits are being added in this step
            }
        }
        return sum;  //returning the sum
    }
}

Output:

Sum of numbers in the string: 36

In the above program, we hardcoded the string. Now, let’s see whether it works with user input or not:

import java.util.*;
public class Main
{
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);   //to take input from user
	    System.out.println("Please enter a string mixed with numbers: "); //prompting user to enter a string
	    String str = sc.nextLine();   //taking input from user
		System.out.println("Sum of numbers in the string: " + string_num_sum(str));  //calling the method and printing the result
	}
	public static int string_num_sum(String str)  //method that checks whether a character is a digit and add it to the sum
	{
       int sum = 0;
        for(int i = 0; i < str.length() ; i++)   //looping through the string
        {
            if( Character.isDigit(str.charAt(i)) )  //checking if the character at certain position is digit or not
            {
                sum = sum + Character.getNumericValue(str.charAt(i));  //digits are being added in this step
            }
        }
        return sum;  //returning the sum
    }
}

Output: 

Please enter a string mixed with numbers: 
73571ng 57r1ng
Sum of numbers in the string: 36

From the output of both programs, you can see that there is no difference in both. 

1 Comment

Hi, Hafsa Rao.. You explained well..

I want to know if I want to calculate the multiplication of the numbers in string how will i do that? Can you write post?

 

Thanks