Input validation for java nCr
This commit is contained in:
parent
4b71f72875
commit
d111c64825
1 changed files with 23 additions and 11 deletions
|
@ -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);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue