Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://dropmefiles.com/Sl6GS
- package labrab4;
- public abstract class ComLineParser {
- // массив строк для хранения ключей
- String [] keys;
- // массив строк для хранения разделителей
- String [] delimeters;
- // варианты завершения разбора командной строки
- public enum SwitchStatus { NoError, Error, ShowUsage };
- public ComLineParser(String[] keys, String[] delimeters) {
- this.keys = keys;
- this.delimeters = delimeters;
- }
- public ComLineParser(String[] keys) {
- this(keys, new String[]{"/","-"});
- }
- // выводит подсказку с форматом командной строки в случае ошибки
- public abstract void OnUsage(String errorKey);
- // вызывается для каждого найденного ключа в командной строке - КОГДА ОН ВЫЗЫВАЕТСЯ?
- public SwitchStatus OnSwitch(String key, String keyValue){
- System.out.println("key: " + key + "; keyValue: " + keyValue);
- return SwitchStatus.NoError;
- }
- public final boolean Parse(String [] args){
- SwitchStatus ss = SwitchStatus.NoError;
- int argNum;
- for (argNum = 0; (ss == SwitchStatus.NoError) && (argNum < args.length); argNum++) {
- // провера наличия правильного разделителя
- boolean isDelimeter = false;
- for (int n = 0; !isDelimeter && (n < delimeters.length); n++) {
- isDelimeter = args[argNum].regionMatches(0,delimeters[n], 0, 1);
- }
- if (isDelimeter) {
- // проверка наличия правильного ключа после правильного разделителя
- boolean isKey = false;
- int i;
- for (i = 0; !isKey && (i < keys.length); i++) {
- isKey = args[argNum].toUpperCase().regionMatches(1, keys[i].toUpperCase(), 0, 1);
- if (isKey) {
- // ИСПРАВИТЬ
- ss = OnSwitch(args[argNum].substring(0, 2),args[argNum].substring(2));
- break;
- }
- }
- if (!isKey) ss = SwitchStatus.Error;
- }
- else {
- ss=SwitchStatus.Error;
- break;
- }
- }
- if (ss == SwitchStatus.ShowUsage) OnUsage(null);
- if (ss == SwitchStatus.Error) OnUsage((argNum == args.length) ? null : args[argNum]);
- return true;
- }
- }
- ========================================================================================================
- package labrab4;
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.Reader;
- import java.io.StringReader;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.StringTokenizer;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class WordCount {
- public static String testString = "In a hole in the ground there lived a hobbit. Not a nasty, "
- + "dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a "
- + "dry, bare, sandy hole with nothing in it to sit down on or to eat: it was a hobbit-hole, "
- + "and that means comfort.";
- private String inFile;
- private String outFile;
- Map<String, Integer> words = new HashMap<>();
- public WordCount(String inFile, String outFile) {
- this.inFile = inFile;
- this.outFile = outFile;
- }
- public String getInFile() {
- return inFile;
- }
- public String getOutFile() {
- return outFile;
- }
- public Map<String, Integer> getWords() {
- return words;
- }
- public void countWords(){
- Reader reader = null;
- if (inFile == null) {
- reader = new StringReader(testString);
- }
- else if (inFile != null) {
- try {
- reader = new FileReader(inFile);
- } catch (FileNotFoundException ex) {
- Logger.getLogger(WordCount.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- BufferedReader br=new BufferedReader(reader);
- try {
- for (String line = br.readLine(); line != null; line = br.readLine()){
- StringTokenizer st = new StringTokenizer(line, " \t\n\r\f;,.)(\"\'?");
- // проверить условие
- while (st.hasMoreTokens()){
- String token = st.nextToken();
- if (this.getWords().containsKey(token)){
- int value = words.get(token);
- words.put(token, value+1);
- }
- else {
- words.put(token, 1);
- }
- }
- }
- } catch (IOException ex) {
- Logger.getLogger(WordCount.class.getName()).log(Level.SEVERE, null, ex);
- }
- try {
- br.close();
- } catch (IOException ex) {
- Logger.getLogger(WordCount.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- ========================================================================================================
- package labrab4;
- public class SimpleParser extends ComLineParser{
- public SimpleParser(String[] keys) {
- super(keys);
- }
- public SimpleParser(String[] keys, String[] delimeters) {
- super(keys, delimeters);
- }
- private String inFile;
- private String outFile;
- public String getInFile() {
- return inFile;
- }
- public String getOutFile() {
- return outFile;
- }
- @Override
- public void OnUsage(String errorKey){
- if (errorKey != null)
- System.out.println("Command-line switch error:" + errorKey);
- System.out.println("формат ком.строки: имяПрограммы [-r<input-fileName>] [-w<output-fileName>]");
- System.out.println(" -? показать Help файл");
- System.out.println(" -r задать имя входного файла");
- System.out.println(" -w выполнить вывод в указанный файл");
- }
- @Override
- public SwitchStatus OnSwitch(String key, String keyValue) {
- SwitchStatus status = SwitchStatus.NoError;
- switch (key){
- case "-?":
- status = SwitchStatus.ShowUsage;
- case "-r":
- if (keyValue.length() != 0) {
- inFile=keyValue;
- }
- else{
- //OnUsage("empty value");
- status = SwitchStatus.Error;
- }
- case "-w":
- if (keyValue.length() != 0) {
- outFile=keyValue;
- }
- else{
- //OnUsage("empty value");
- status = SwitchStatus.Error;
- }
- }
- System.out.println("key: " + key + "; keyValue: " + keyValue);
- return status;
- }
- }
- ========================================================================================================
- package labrab4;
- import java.util.Map;
- import java.util.Set;
- public class MyCounter {
- public static void main(String[] args) {
- SimpleParser sp = new SimpleParser(new String[] {"r", "w"});
- sp.Parse(args);
- // WordCount wc = new WordCount(null,null);
- WordCount wc = new WordCount( sp.getInFile(), null);
- System.out.println("Имя входного файла для подсчёта: " + sp.getInFile());
- wc.countWords();
- // Получаем набор элементов
- Set<Map.Entry<String, Integer>> set = wc.getWords().entrySet();
- // Отобразим набор
- for (Map.Entry<String, Integer> me : set) {
- System.out.print(me.getKey() + ": ");
- System.out.println(me.getValue());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement