Skip to content

Commit

Permalink
Merge pull request #357 from yixiann/modify-view-command
Browse files Browse the repository at this point in the history
Modify view command to show error for negative index
  • Loading branch information
RichDom2185 authored Oct 27, 2022
2 parents 26e6a54 + c3bbf34 commit 4390761
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/main/java/seedu/foodrem/commons/util/StringUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -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} <br>
* 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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) {
Expand Down

0 comments on commit 4390761

Please sign in to comment.