Daryan997

Extract numbers

Apr 19th, 2021
652
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×