There is the following task: the user enters a command with parameters into the console and depending on the command and parameters certain actions are performed. For example, the console introduces: insert 2 10

I need to read the insert command and pass it to a method that implements insert parameters 2 and 10. I went this way:

Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String[] s = str.split(" "); int firstParam = new Integer(s[1]); int secondParam = new Integer(s[2]); if (s[0].equals("insert")) { insert(firstParam, secondParam); } 

But you need to check the correctness of the input command and parameters. Those. insert 2 10 15 is suddenly entered. Then the code will also be executed. But this is not true. And if it is entered: one one one then a NumberFormatException will be thrown. It turns out I need to check that there are only 3 elements in the array, then check all the elements to match the expected data and catch the controls - am I digging in the right direction or is there a more elegant solution?

  • one
    To move to an elegant solution, start by learning the basics of compilation. There are all grammars, lexical, syntactic analyzers, etc. bredyatina. The theory underlying the whole computer thought (academies didn’t go through, I don’t know the name itself), and tools to facilitate the task (flex, bison, antlr, etc.). - Sergey

1 answer 1

 public class Result{ //класс для представления результата выполнения команд } public abstract class MyCommandCallback{ void onComplete(Result result){ //обработка успешного результата } void onError(Result result){ //обработка ошибки } } public interface MyCommandInterface{ MyCommand(String[] params); void execute(MyCommandCallback callback); } class Insert implements MyCommandInterface{ Insert(String[] params){ //тут разбираете свои аргументы и проверяете их на количество и корректность } void execute(MyCommandCallback callback){ //тут производите необходимые действия и, в зависимости //от успешности, вызываете callback.onComplete() или callback.onError() } } 

well and in the main code

 Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String[] s = str.split(" "); if(s.length()==0) throw new Exception(); MyCommandInterface work; switch(s[0]){ case "insert": work=new Insert(s); break; //..... default: throw new Exception(); } work.execute(new MyCommandCallback(){/*.....*/});