From 77d2c4dd0460f82c182193a2b564b9234e9c67b9 Mon Sep 17 00:00:00 2001 From: XavierLiau34 Date: Thu, 14 Mar 2024 01:31:19 +0800 Subject: [PATCH] Parser --- src/main/java/seedu/binbash/Parser.java | 44 ++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/src/main/java/seedu/binbash/Parser.java b/src/main/java/seedu/binbash/Parser.java index 09d25b3c17..de6f04c7a3 100644 --- a/src/main/java/seedu/binbash/Parser.java +++ b/src/main/java/seedu/binbash/Parser.java @@ -1,2 +1,44 @@ -package seedu.binbash;public class Parser { +package seedu.binbash; + +import java.util.regex.Matcher; + +import seedu.binbash.command.Command; +import seedu.binbash.command.DeleteCommand; +import seedu.binbash.command.ListCommand; + +public class Parser { + private final ItemList itemList; + + public Parser(ItemList itemList) { + this.itemList = itemList; + } + + public Command parseCommand(String userInput) { + String[] tokens = userInput.trim().split("\\s+", 2); + String commandString = tokens[0].toLowerCase(); + String arguments = tokens.length > 1 ? tokens[1] : ""; + + switch (commandString) { + case "delete": + return parseDeleteCommand(arguments); + case "list": + return parseListCommand(arguments); + default: + return null; + } + } + + private Command parseDeleteCommand(String arguments) { + Matcher matcher = DeleteCommand.COMMAND_FORMAT.matcher(arguments); + if (matcher.matches()) { + int index = Integer.parseInt(matcher.group("index")); + return new DeleteCommand(itemList, index); + } else { + return null; + } + } + + private Command parseListCommand(String arguments) { + return new ListCommand(itemList); + } }