Created
March 26, 2022 09:16
-
-
Save gicappa/c03c30eaceef774b857afbfd232077ca 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
package gk; | |
import static java.math.BigDecimal.ZERO; | |
import java.math.BigDecimal; | |
import java.util.Scanner; | |
public class AmountParser { | |
Scanner sc = new Scanner(System.in); | |
public static void main(String[] args) { | |
var parser = new AmountParser(); | |
var value = parser.inputBigDecimalValue("> ", BigDecimal.ONE, BigDecimal.TEN); | |
System.out.println("The selected value is " + value); | |
} | |
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; | |
} | |
private boolean promptAndGetNextInput(String prompt) { | |
System.out.print(prompt); | |
return sc.hasNext(); | |
} | |
private boolean isInputValid(String line) { | |
try { | |
new BigDecimal(line); | |
return true; | |
} catch (NumberFormatException nfe) { | |
return false; | |
} | |
} | |
private boolean isAmountInRange(BigDecimal amount, BigDecimal min, BigDecimal max) { | |
return amount.compareTo(min) >= 0 && amount.compareTo(max) <= 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment