001 package org.bukkit.conversations;
002
003 import org.apache.commons.lang.math.NumberUtils;
004
005 /**
006 * NumericPrompt is the base class for any prompt that requires a {@link
007 * Number} response from the user.
008 */
009 public abstract class NumericPrompt extends ValidatingPrompt{
010 public NumericPrompt() {
011 super();
012 }
013
014 @Override
015 protected boolean isInputValid(ConversationContext context, String input) {
016 return NumberUtils.isNumber(input) && isNumberValid(context, NumberUtils.createNumber(input));
017 }
018
019 /**
020 * Override this method to do further validation on the numeric player
021 * input after the input has been determined to actually be a number.
022 *
023 * @param context Context information about the conversation.
024 * @param input The number the player provided.
025 * @return The validity of the player's input.
026 */
027 protected boolean isNumberValid(ConversationContext context, Number input) {
028 return true;
029 }
030
031 @Override
032 protected Prompt acceptValidatedInput(ConversationContext context, String input) {
033 try
034 {
035 return acceptValidatedInput(context, NumberUtils.createNumber(input));
036 } catch (NumberFormatException e) {
037 return acceptValidatedInput(context, NumberUtils.INTEGER_ZERO);
038 }
039 }
040
041 /**
042 * Override this method to perform some action with the user's integer
043 * response.
044 *
045 * @param context Context information about the conversation.
046 * @param input The user's response as a {@link Number}.
047 * @return The next {@link Prompt} in the prompt graph.
048 */
049 protected abstract Prompt acceptValidatedInput(ConversationContext context, Number input);
050
051 @Override
052 protected String getFailedValidationText(ConversationContext context, String invalidInput) {
053 if (NumberUtils.isNumber(invalidInput)) {
054 return getFailedValidationText(context, NumberUtils.createNumber(invalidInput));
055 } else {
056 return getInputNotNumericText(context, invalidInput);
057 }
058 }
059
060 /**
061 * Optionally override this method to display an additional message if the
062 * user enters an invalid number.
063 *
064 * @param context Context information about the conversation.
065 * @param invalidInput The invalid input provided by the user.
066 * @return A message explaining how to correct the input.
067 */
068 protected String getInputNotNumericText(ConversationContext context, String invalidInput) {
069 return null;
070 }
071
072 /**
073 * Optionally override this method to display an additional message if the
074 * user enters an invalid numeric input.
075 *
076 * @param context Context information about the conversation.
077 * @param invalidInput The invalid input provided by the user.
078 * @return A message explaining how to correct the input.
079 */
080 protected String getFailedValidationText(ConversationContext context, Number invalidInput) {
081 return null;
082 }
083 }