Daryan997

Extract numbers v2

Apr 19th, 2021
1,248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1. package extractnumbers2;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class ExtractNumbers2 {
  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.         String stringNumber = "";
  12.         int sum = 0;
  13.         int count = 0;
  14.         System.out.println("List of numbers:");
  15.         for (int i = 0; i < text.length(); i++) {
  16.             char charact = text.charAt(i);
  17.             if (charact > 47 && charact < 58) {
  18.                 String inp = String.valueOf(text.charAt(i));
  19.                 stringNumber = stringNumber.concat(inp);
  20.             }
  21.            
  22.             if ((!(charact > 47 && charact < 58) || i == text.length() - 1) && !stringNumber.isEmpty()) {
  23.                 System.out.println(stringNumber);
  24.                 sum += Integer.parseInt(stringNumber);
  25.                 stringNumber = "";
  26.                 count++;
  27.             }
  28.         }
  29.         System.out.println("The text has " + count + " numbers.");
  30.         System.out.println("Sum of numbers = " + sum);
  31.     }
  32.  
  33. }
  34.  
Add Comment
Please, Sign In to add comment