Daryan997

Extract numbers

Apr 19th, 2021
845
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. package extractnumbers;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class ExtractNumbers {
  6.  
  7.     public static void main(String[] args) {
  8.         Scanner input = new Scanner(System.in);
  9.         System.out.print("Input: ");
  10.         String text = input.nextLine();
  11.         text = text.replaceAll("[^0-9]", " ");
  12.         text = text.trim();
  13.         text = text.replaceAll(" +", " ");
  14.         String stringNumber = "";
  15.         int sum = 0;
  16.         int count = 0;
  17.         System.out.println("List of numbers:");
  18.         for (int i = 0; i < text.length(); i++) {
  19.             char charact = text.charAt(i);
  20.             if (charact > 47 && charact < 58) {
  21.                 String inp = String.valueOf(text.charAt(i));
  22.                 stringNumber = stringNumber.concat(inp);
  23.             }
  24.            
  25.             if (charact == ' ' || i == text.length() - 1) {
  26.                 System.out.println(stringNumber);
  27.                 sum += Integer.parseInt(stringNumber);
  28.                 stringNumber = "";
  29.                 count++;
  30.             }
  31.         }
  32.         System.out.println("The text has " + count + " numbers.");
  33.         System.out.println("Sum of numbers = " + sum);
  34.     }
  35.  
  36. }
  37.  
Add Comment
Please, Sign In to add comment