Advertisement
badtrips

LabRab4

Jun 28th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.35 KB | None | 0 0
  1. // https://dropmefiles.com/Sl6GS
  2.  
  3. package labrab4;
  4.  
  5. public abstract class ComLineParser {
  6.    
  7.     // массив строк для хранения ключей
  8.     String [] keys;
  9.     // массив строк для хранения разделителей
  10.     String [] delimeters;
  11.     // варианты завершения разбора командной строки
  12.     public enum SwitchStatus { NoError, Error, ShowUsage };
  13.  
  14.     public ComLineParser(String[] keys, String[] delimeters) {
  15.         this.keys = keys;
  16.         this.delimeters = delimeters;
  17.     }
  18.  
  19.     public ComLineParser(String[] keys) {
  20.         this(keys, new String[]{"/","-"});
  21.     }
  22.    
  23.     // выводит подсказку с форматом командной строки в случае ошибки
  24.     public abstract void OnUsage(String errorKey);
  25.  
  26.     // вызывается для каждого найденного ключа в командной строке - КОГДА ОН ВЫЗЫВАЕТСЯ?
  27.     public SwitchStatus OnSwitch(String key, String keyValue){
  28.         System.out.println("key: " + key + "; keyValue: " + keyValue);
  29.         return SwitchStatus.NoError;
  30.     }
  31.    
  32.     public final boolean Parse(String [] args){
  33.         SwitchStatus ss = SwitchStatus.NoError;    
  34.         int argNum;
  35.         for (argNum = 0; (ss == SwitchStatus.NoError) && (argNum < args.length); argNum++) {
  36.            // провера наличия правильного разделителя
  37.             boolean isDelimeter = false;
  38.             for (int n = 0; !isDelimeter && (n < delimeters.length); n++) {
  39.                  isDelimeter = args[argNum].regionMatches(0,delimeters[n], 0, 1);
  40.             }
  41.             if (isDelimeter) {
  42.             // проверка наличия правильного ключа после правильного разделителя
  43.                 boolean isKey = false;
  44.                 int i;
  45.                 for (i = 0; !isKey && (i < keys.length); i++) {
  46.                     isKey = args[argNum].toUpperCase().regionMatches(1, keys[i].toUpperCase(), 0, 1);    
  47.                     if (isKey) {
  48.                         // ИСПРАВИТЬ
  49.                        
  50.                         ss = OnSwitch(args[argNum].substring(0, 2),args[argNum].substring(2));
  51.                         break;
  52.                     }
  53.                 }
  54.                
  55.                 if (!isKey) ss = SwitchStatus.Error;
  56.             }
  57.             else {
  58.                 ss=SwitchStatus.Error;
  59.                 break;
  60.             }
  61.         }
  62.         if (ss == SwitchStatus.ShowUsage)    OnUsage(null);
  63.         if (ss == SwitchStatus.Error)        OnUsage((argNum == args.length) ? null : args[argNum]);
  64.         return true;
  65.     }
  66.    
  67. }
  68.  
  69. ========================================================================================================
  70.  
  71. package labrab4;
  72.  
  73. import java.io.BufferedReader;
  74. import java.io.FileNotFoundException;
  75. import java.io.FileReader;
  76. import java.io.IOException;
  77. import java.io.Reader;
  78. import java.io.StringReader;
  79. import java.util.HashMap;
  80. import java.util.Map;
  81. import java.util.StringTokenizer;
  82. import java.util.logging.Level;
  83. import java.util.logging.Logger;
  84.  
  85. public class WordCount {
  86.    
  87.     public static String testString = "In a hole in the ground there lived a hobbit. Not a nasty, "
  88.             + "dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a "
  89.             + "dry, bare, sandy hole with nothing in it to sit down on or to eat: it was a hobbit-hole, "
  90.             + "and that means comfort.";
  91.    
  92.     private String inFile;
  93.     private String outFile;
  94.     Map<String, Integer> words = new HashMap<>();
  95.  
  96.     public WordCount(String inFile, String outFile) {
  97.         this.inFile = inFile;
  98.         this.outFile = outFile;
  99.     }
  100.    
  101.     public String getInFile() {
  102.         return inFile;
  103.     }
  104.     public String getOutFile() {
  105.         return outFile;
  106.     }
  107.     public Map<String, Integer> getWords() {
  108.         return words;
  109.     }
  110.    
  111.     public void countWords(){
  112.         Reader reader = null;
  113.         if (inFile == null) {
  114.             reader = new StringReader(testString);
  115.         }
  116.         else if (inFile != null) {
  117.             try {
  118.                 reader = new FileReader(inFile);
  119.             } catch (FileNotFoundException ex) {
  120.                 Logger.getLogger(WordCount.class.getName()).log(Level.SEVERE, null, ex);
  121.             }
  122.         }
  123.         BufferedReader br=new BufferedReader(reader);
  124.         try {
  125.             for (String line = br.readLine(); line != null; line = br.readLine()){
  126.                 StringTokenizer st = new StringTokenizer(line, " \t\n\r\f;,.)(\"\'?");
  127.                 // проверить условие
  128.                 while (st.hasMoreTokens()){
  129.                     String token = st.nextToken();
  130.                     if (this.getWords().containsKey(token)){
  131.                         int value = words.get(token);
  132.                         words.put(token, value+1);
  133.                     }
  134.                     else {
  135.                         words.put(token, 1);
  136.                     }
  137.                 }
  138.             }
  139.         } catch (IOException ex) {
  140.             Logger.getLogger(WordCount.class.getName()).log(Level.SEVERE, null, ex);
  141.         }
  142.         try {
  143.             br.close();
  144.         } catch (IOException ex) {
  145.             Logger.getLogger(WordCount.class.getName()).log(Level.SEVERE, null, ex);
  146.         }
  147.     }
  148. }
  149.  
  150.  
  151. ========================================================================================================
  152.  
  153.  
  154. package labrab4;
  155.  
  156. public class SimpleParser extends ComLineParser{
  157.    
  158.     public SimpleParser(String[] keys) {
  159.         super(keys);
  160.     }
  161.     public SimpleParser(String[] keys, String[] delimeters) {
  162.         super(keys, delimeters);
  163.     }
  164.    
  165.     private String inFile;
  166.     private String outFile;
  167.  
  168.     public String getInFile() {
  169.         return inFile;
  170.     }
  171.     public String getOutFile() {
  172.         return outFile;
  173.     }
  174.    
  175.     @Override
  176.     public void OnUsage(String errorKey){
  177.         if (errorKey != null)
  178.             System.out.println("Command-line switch error:" + errorKey);
  179.         System.out.println("формат ком.строки: имяПрограммы [-r<input-fileName>] [-w<output-fileName>]");
  180.     System.out.println("   -?  показать Help файл");
  181.     System.out.println("   -r  задать имя входного файла");
  182.     System.out.println("   -w  выполнить вывод в указанный файл");
  183.     }
  184.  
  185.     @Override
  186.     public SwitchStatus OnSwitch(String key, String keyValue) {
  187.         SwitchStatus status = SwitchStatus.NoError;
  188.         switch (key){
  189.             case "-?":
  190.                 status = SwitchStatus.ShowUsage;
  191.             case "-r":
  192.                 if (keyValue.length() != 0) {
  193.                     inFile=keyValue;
  194.                 }
  195.                 else{
  196.                     //OnUsage("empty value");
  197.                     status = SwitchStatus.Error;
  198.                 }
  199.             case "-w":
  200.                 if (keyValue.length() != 0) {
  201.                     outFile=keyValue;
  202.                 }
  203.                 else{
  204.                     //OnUsage("empty value");
  205.                     status = SwitchStatus.Error;
  206.                 }
  207.         }
  208.         System.out.println("key: " + key + "; keyValue: " + keyValue);
  209.         return status;
  210.     }
  211. }
  212.  
  213. ========================================================================================================
  214.  
  215.  
  216. package labrab4;
  217.  
  218. import java.util.Map;
  219. import java.util.Set;
  220.  
  221. public class MyCounter {
  222.  
  223.     public static void main(String[] args) {
  224.        
  225.         SimpleParser sp = new SimpleParser(new String[] {"r", "w"});
  226.         sp.Parse(args);
  227.  
  228. //        WordCount wc = new WordCount(null,null);
  229.         WordCount wc = new WordCount( sp.getInFile(), null);
  230.         System.out.println("Имя входного файла для подсчёта: " + sp.getInFile());
  231.         wc.countWords();
  232.        
  233.         // Получаем набор элементов
  234.         Set<Map.Entry<String, Integer>> set = wc.getWords().entrySet();
  235.  
  236.         // Отобразим набор
  237.         for (Map.Entry<String, Integer> me : set) {
  238.             System.out.print(me.getKey() + ": ");
  239.             System.out.println(me.getValue());
  240.         }
  241.     }
  242. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement