From c3bbf344994eb5fa5e682cae177b9f59b685699d Mon Sep 17 00:00:00 2001 From: Tan Yi Xian <> Date: Fri, 28 Oct 2022 03:52:34 +0800 Subject: [PATCH] Modify view to show error for negative index --- .../seedu/foodrem/commons/util/StringUtil.java | 16 ++++++++++++++-- .../itemcommandparser/ViewCommandParser.java | 11 +++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/java/seedu/foodrem/commons/util/StringUtil.java b/src/main/java/seedu/foodrem/commons/util/StringUtil.java index 4cc6fcc2052..09388c45097 100644 --- a/src/main/java/seedu/foodrem/commons/util/StringUtil.java +++ b/src/main/java/seedu/foodrem/commons/util/StringUtil.java @@ -83,11 +83,23 @@ public static String getDetails(Throwable t) { * @throws NullPointerException if {@code s} is null. */ public static boolean isNonZeroUnsignedInteger(String s) { + return isInteger(s) && Integer.parseInt(s) > 0; + } + + /** + * Returns {@code true} if {@code s} represents an integer + * e.g. {@code Integer.MIN_VALUE} -3, -2, -1, 0, 1, 2, 3, ..., {@code Integer.MAX_VALUE}
+ * Will return {@code false} for any other non-null string input + * e.g. empty string, "0", "+1", and " 2 " (untrimmed), "3 0" (contains whitespace), "1 a" (contains letters) + * + * @throws NullPointerException if {@code s} is null. + */ + public static boolean isInteger(String s) { requireNonNull(s); try { - int value = Integer.parseInt(s); - return value > 0 && !s.startsWith("+"); // "+1" is successfully parsed by Integer#parseInt(String) + Integer.parseInt(s); + return !s.startsWith("+"); // "+1" is successfully parsed by Integer#parseInt(String) } catch (NumberFormatException nfe) { return false; } diff --git a/src/main/java/seedu/foodrem/logic/parser/itemcommandparser/ViewCommandParser.java b/src/main/java/seedu/foodrem/logic/parser/itemcommandparser/ViewCommandParser.java index a7cb322c658..c7d77116883 100644 --- a/src/main/java/seedu/foodrem/logic/parser/itemcommandparser/ViewCommandParser.java +++ b/src/main/java/seedu/foodrem/logic/parser/itemcommandparser/ViewCommandParser.java @@ -4,6 +4,7 @@ import seedu.foodrem.commons.core.Messages; import seedu.foodrem.commons.core.index.Index; +import seedu.foodrem.commons.util.StringUtil; import seedu.foodrem.logic.commands.itemcommands.ViewCommand; import seedu.foodrem.logic.parser.Parser; import seedu.foodrem.logic.parser.ParserUtil; @@ -23,6 +24,16 @@ public ViewCommand parse(String args) throws ParseException { requireNonNull(args); Index index; + String trimmedArgument = args.trim(); + + if (!StringUtil.isInteger(trimmedArgument)) { + throw new ParseException(String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, ViewCommand.getUsage())); + } + + if (!StringUtil.isNonZeroUnsignedInteger(trimmedArgument)) { + throw new ParseException("The index should be a non-negative number."); + } + try { index = ParserUtil.parseIndex(args); } catch (ParseException pe) {