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;
|
package calculators;
|
||||||
|
import java.util.InputMismatchException;
|
||||||
import java.util.Scanner;
|
import java.util.Scanner;
|
||||||
|
|
||||||
class CombinationCalculator {
|
class CombinationCalculator {
|
||||||
|
private static Scanner scanner = new Scanner(System.in);
|
||||||
|
|
||||||
private static int factorial(int n) {
|
private static int factorial(int n) {
|
||||||
int res = 1;
|
int res = 1;
|
||||||
|
|
||||||
|
@ -16,19 +19,28 @@ class CombinationCalculator {
|
||||||
return factorial(n) / (factorial(r) * factorial(n - r));
|
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) {
|
public static void main(String[] args) {
|
||||||
// Open a scanner and take the relevant inputs
|
// Take inputs
|
||||||
Scanner scan = new Scanner(System.in);
|
int n = intInput("Please input the value for n: ");
|
||||||
|
int r = intInput("Please input the value for r: ");
|
||||||
System.out.print("Please input the value for n: ");
|
scanner.close();
|
||||||
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();
|
|
||||||
|
|
||||||
|
// Calculate the result
|
||||||
int result = nCr(n, r);
|
int result = nCr(n, r);
|
||||||
System.out.println(result);
|
System.out.println(result);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue