Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package extractnumbers;
- import java.util.Scanner;
- public class ExtractNumbers {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("Input: ");
- String text = input.nextLine();
- text = text.replaceAll("[^0-9]", " ");
- text = text.trim();
- text = text.replaceAll(" +", " ");
- String stringNumber = "";
- int sum = 0;
- int count = 0;
- System.out.println("List of numbers:");
- for (int i = 0; i < text.length(); i++) {
- char charact = text.charAt(i);
- if (charact > 47 && charact < 58) {
- String inp = String.valueOf(text.charAt(i));
- stringNumber = stringNumber.concat(inp);
- }
- if (charact == ' ' || i == text.length() - 1) {
- System.out.println(stringNumber);
- sum += Integer.parseInt(stringNumber);
- stringNumber = "";
- count++;
- }
- }
- System.out.println("The text has " + count + " numbers.");
- System.out.println("Sum of numbers = " + sum);
- }
- }
Add Comment
Please, Sign In to add comment