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?