Skip to content

Instantly share code, notes, and snippets.

@gicappa
Last active March 26, 2022 09:28
Show Gist options
  • Save gicappa/cc7a56a6210040e0be0d15dd4cab4eb9 to your computer and use it in GitHub Desktop.
Save gicappa/cc7a56a6210040e0be0d15dd4cab4eb9 to your computer and use it in GitHub Desktop.
/**
* Reads only valid amount from standard output and returns
* it to the caller.
*
* @param prompt to be shown to the user to mark where to input
* @param min amount allowed
* @param max amount allowed
* @return the valid amount
*/
public BigDecimal inputBigDecimalValue(String prompt, BigDecimal min, BigDecimal max) {
while (promptAndGetNextInput(prompt)) {
String input = sc.nextLine();
if (!isInputValid(input)) {
System.out.println("Invalid input.");
continue;
}
var amount = new BigDecimal(input);
if (!isAmountInRange(amount, min, max)) {
System.out.println("Input out of range from " + min + " to " + max);
continue;
}
return amount;
}
return ZERO;
}
// The actual business logic of the parser
private boolean isAmountInRange(BigDecimal amount, BigDecimal min, BigDecimal max) {
return amount.compareTo(min) >= 0 && amount.compareTo(max) <= 0;
}
// Checks if the line input is valid or not
private boolean isInputValid(String line) {
try {
new BigDecimal(line);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
// Convenience method to prompt before each new input
private boolean promptAndGetNextInput(String prompt) {
System.out.print(prompt);
return sc.hasNext();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment