Java Exercises: Sum of all numerical values embedded in a sentence
Java Basic: Exercise-236 with Solution
Write a Java program to sum of 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.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;
public class Main
{
public static void main(String arg[])
{
Scanner in = new Scanner(System.in);
int count =0;
String tmp = "0";
System.out.println("Input some text and numeric values:");
char ch[]=in.nextLine().toCharArray();
for(int i=0; i<ch.length; i++)
{
while(i<ch.length&&(Character.isDigit(ch[i])))
{
tmp+=ch[i];
i++;
}
count+=Integer.valueOf(tmp);
tmp="0";
}
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:
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.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework