SHARE
TWEET

regex-exam

a guest Apr 18th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package exam;
  2.  
  3. import exam.engines.Engine;
  4.  
  5. import java.util.Scanner;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class Main {
  10.     public static void main(String[] args) {
  11.         Scanner scanner = new Scanner(System.in);
  12.         // TODO
  13. //        Engine engine = new Engine();
  14. //        engine.run();
  15.  
  16.         int n = Integer.parseInt(scanner.nextLine());
  17.         Pattern pattern = Pattern.compile("^n:(?<name>[^;]+);t:(?<kind>[^;]+);c--(?<country>[A-Za-z\\s]+)$");
  18.         int totalWeight = 0;
  19.  
  20.         for (int i = 0; i < n; i++) {
  21.             String input = scanner.nextLine();
  22.             Matcher matcher = pattern.matcher(input);
  23.  
  24.             StringBuilder nameResult = new StringBuilder();
  25.             StringBuilder kindResult = new StringBuilder();
  26.  
  27.             int animalWeight = 0;
  28.  
  29.             if (matcher.find()) {
  30.                 String animalName = matcher.group("name");
  31.                 String animalKind = matcher.group("kind");
  32.                 String country = matcher.group("country");
  33.  
  34.                 for (int j = 0; j < animalName.length(); j++) {
  35.                     char currChar = animalName.charAt(j);
  36.  
  37.                     if (Character.isLetter(currChar)) {
  38.                         nameResult.append(currChar);
  39.                     }
  40.  
  41.                     if (Character.isDigit(currChar)) {
  42.                         animalWeight += Character.getNumericValue(currChar);
  43.                     }
  44.                 }
  45.  
  46.                 for (int j = 0; j < animalKind.length(); j++) {
  47.                     char currChar = animalKind.charAt(j);
  48.  
  49.                     if (Character.isLetter(currChar)) {
  50.                         kindResult.append(currChar);
  51.                     }
  52.  
  53.                     if (Character.isDigit(currChar)) {
  54.                         animalWeight += Character.getNumericValue(currChar);
  55.                     }
  56.                 }
  57.  
  58.                 totalWeight += animalWeight;
  59.                 System.out.println(String.format("%s is a %s from %s", nameResult, kindResult, country));
  60.             }
  61.         }
  62.  
  63.         System.out.printf("Total weight of animals: %dKG\n", totalWeight);
  64.     }
  65. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top