w3resource

Java: Sum of all numerical values embedded in a sentence

Java Basic: Exercise-236 with Solution

Write a Java program to sum all numerical values (positive integers) embedded in a sentence.

Input:
Sentences with positive integers are given over multiple lines. Each line is a character string containing one-byte alphanumeric characters, symbols, spaces, or an empty line. However the input is 80 characters or less per line and the sum is 10,000 or less.

Visual Presentation:

Java Basic Exercises: Sum of all numerical values embedded in a sentence.

Sample Solution:

Java Code:

// Importing the Scanner class from java.util package
import java.util.Scanner;

// Main class named "Main"
public class Main
{
    // Main method to execute the program
    public static void main(String arg[])
    {
        // Creating a Scanner object to read input from the console
        Scanner in = new Scanner(System.in);

        // Initializing variables to store the count and temporary numeric value
        int count = 0;
        String tmp = "0";

        // Prompting the user to input some text and numeric values
		System.out.println("Input some text and numeric values:");

        // Converting the input string to a character array
        char ch[] = in.nextLine().toCharArray();

        // Looping through each character in the array
        for(int i = 0; i < ch.length; i++)
        {
            // Checking if the current character is a digit
            while(i < ch.length && (Character.isDigit(ch[i])))
            {
                // Concatenating digits to form a temporary numeric value
                tmp += ch[i];
                i++;
            }

            // Adding the numeric value to the count
            count += Integer.valueOf(tmp);

            // Resetting the temporary numeric value
            tmp = "0";
        }

        // Displaying the sum of the numeric values
		System.out.println("\nSum of the numeric values:");
        System.out.println(count);
    }
} 

Sample Output:

Input some text and numeric values:
5 apple and 10 orange are rotten in the basket

Sum of the numeric values:
15

Flowchart:

Flowchart: Sum of all numerical values embedded in a sentence.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to test whether AB and CD are orthogonal or not.
Next: Write a Java program to read the mass data and find the number of islands.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.