Im trying to configure my code to tell the user to re enter a number, taking them back to the scanner if it falls outside of my specified range of 25
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0)
System.out.println("Positive numbers only");// if number entered is negative
else if (number > 25)
System.out.println("Number to large to print");
else if (number <= 1)// if number entered is 0 or 1
System.out.printf("The factorial of " number " is equal to " factorial);
else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and storing again in factorial variable
}
System.out.println("The factorial of " number " is equal to " factorial);
}
CodePudding user response:
To simplify the logic, you could extract it to the separate method. The logic itself is pretty strightforward:
- in loop
- ask a number
- check if the number within the bounds
- if not repeate or return if yes
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int num = getNumberWithin(scan, 1, 25);
}
private static int getNumberWithin(Scanner scan, int lo, int hi) {
while (true) {
System.out.format("Enter a number between %d and %d: ", lo, hi);
int num = scan.nextInt();
if (num >= lo && num <= hi)
return num;
System.err.format("The number should be between %d and %d\n", lo, hi);
System.out.println();
}
}
CodePudding user response:
boolean correctInputn= false;
while(!correctInputn)
{
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0)
{System.out.println("Positive numbers only");// if number entered is negative
correctInputn = false; continue;} // if user enters number less than 0 loops back to code start
else if (number > 25)
{ System.out.println("Number to large to print");
correctInputn = false; continue;} // if user enters number over 25 loops back to code start
else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and stored again in factorial variable
}
System.out.println("The factorial of " number " is equal to " factorial);
break;
}
}