import java.util.*;
import java.text.*;
public class FactorialApp
{
public static void main(String[] args)
{
// create a Scanner object named sc and intializ variables
Scanner sc = new Scanner(System.in);
// perform Factorial application when user enters "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//get input from user
int power = getIntWithinRange(sc,
"Enter number greater than 0 and less than 20: ", 0, 21);
long number = 1;
//use a for loop to calculate the power
for (int i = 1; i<= power; i++)
{
number = number * i;
}
System.out.println("The factorial is: " + number + "\n");
String cont = "";
System.out.print("Continue? (y/n)");
cont = sc.next();
sc.nextLine();
System.out.println();
}
}
public static int getInt (Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println
("Error! Invalid integer value. Try again.");
}
sc.nextLine(); //discard any other data entered on the line
}
return i;
}
public static int getIntWithinRange (Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println("Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
}//end program
I Only want to accept “y/Y” or “n/N” from the user for the continue prompt (i.e., include validations for the String as well as the numeric input)