Input validation for java nCr

This commit is contained in:
newt 2024-10-09 18:02:37 +01:00
parent d2a18f7764
commit e340b1888a

View file

@ -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);
}