From d111c6482505605a9353095c3be1a30d217c8a1b Mon Sep 17 00:00:00 2001 From: newtykins Date: Tue, 21 Dec 2021 20:33:59 +0000 Subject: [PATCH] Input validation for java nCr --- java/calculators/ncr.java | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/java/calculators/ncr.java b/java/calculators/ncr.java index a5e4d57..b5bebe1 100644 --- a/java/calculators/ncr.java +++ b/java/calculators/ncr.java @@ -1,7 +1,10 @@ package calculators; +import java.util.InputMismatchException; import java.util.Scanner; class CombinationCalculator { + private static Scanner scanner = new Scanner(System.in); + private static int factorial(int n) { int res = 1; @@ -16,19 +19,28 @@ class CombinationCalculator { return factorial(n) / (factorial(r) * factorial(n - r)); } + private static int intInput(String message) { + int value = -1; + + while (value < 0) { + try { + System.out.print(message); + value = scanner.nextInt(); + } catch (InputMismatchException e) { + scanner.next(); + } + } + + return value; + } + public static void main(String[] args) { - // Open a scanner and take the relevant inputs - Scanner scan = new Scanner(System.in); - - System.out.print("Please input the value for n: "); - int n = scan.nextInt(); - - System.out.print("Please input the value for r: "); - int r = scan.nextInt(); - - // Close the scanner, and calculate the result - scan.close(); + // Take inputs + int n = intInput("Please input the value for n: "); + int r = intInput("Please input the value for r: "); + scanner.close(); + // Calculate the result int result = nCr(n, r); System.out.println(result); }