Last active
March 26, 2022 09:28
-
-
Save gicappa/cc7a56a6210040e0be0d15dd4cab4eb9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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