desislava_topuzakova

2. Fancy Barcodes

Aug 6th, 2021
1,575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. public class FancyBarcodes_02 {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.         String regex = "@#+(?<productName>[A-Z][A-Za-z0-9]{4,}[A-Z])@#+";
  9.         Pattern pattern = Pattern.compile(regex);
  10.         int n = Integer.parseInt(scanner.nextLine()); //брой на баркодове
  11.         for (int i = 1; i <= n; i++) {
  12.             String barcode = scanner.nextLine();
  13.             //проверка дали е валиден
  14.             Matcher matcher = pattern.matcher(barcode);
  15.             //валиден -> търсим product group -> печатаме
  16.             if (matcher.find()) {
  17.                 //валиден
  18.                 String productName = matcher.group("productName"); //"Brea0D"
  19.                 StringBuilder productNumber = new StringBuilder(); //"" -> всички цифри от името на продукта
  20.                 for (int index = 0; index < productName.length(); index++) {
  21.                     char currentSymbol = productName.charAt(index);
  22.                     //проверка дали е цифра
  23.                     if (Character.isDigit(currentSymbol)) {
  24.                         productNumber.append(currentSymbol);
  25.                     }
  26.                 }
  27.  
  28.                 //отпечатваме productNumber
  29.                 //ако нямаме цифри
  30.                 if (productNumber.toString().equals("")) {
  31.                     System.out.println("Product group: 00");
  32.                 } else {
  33.                     System.out.printf("Product group: %s%n", productNumber);
  34.                 }
  35.  
  36.             }
  37.             //невалиден -> печатаме
  38.             else {
  39.                 System.out.println("Invalid barcode");
  40.             }
  41.         }
  42.     }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment