Search code examples
javavalidationinputwhile-loopfactorial

Factorial of a positive integer between 1-10. Issue: Works only if valid input is greater than previous input


Everything works fine the first run but if I enter a valid number between 1 and 10 that is lower than the first input, the output basically stays the same.

Inputs following the first only work correctly if they are higher than previous inputs.

import java.util.Scanner;

public class Lab6_2{

  public static void main(String []args){

    //declarations

    Scanner input = new Scanner(System.in);

    char flagContinue;
    int userOneToTen;
    int factorialInteger = 1, counterA = 1;

    //process

    System.out.println("Do you want to start(Y/N):");

    flagContinue = input.next().charAt(0);

    while(flagContinue == 'y' || flagContinue == 'Y'){

      System.out.println("Enter an integer (1 - 10):");

      userOneToTen = input.nextInt();

      while(counterA <= userOneToTen){

          if(userOneToTen <= 0 || userOneToTen > 10){

            System.out.println("Invalid entry. Please enter an integer between 1-10");

            userOneToTen = input.nextInt();

          }//end if

          factorialInteger = factorialInteger * counterA;

          counterA ++;  

        }//end while

      System.out.println(userOneToTen + "!" + factorialInteger);  

      System.out.println("Do you want to start(Y/N):");

      flagContinue = input.next().charAt(0);

      }//end while

  }//end main

}//end class

Solution

  • You have to set counterA AND factorialInteger back to one in the outer while loop.

    counterA = 1;
    factorialInteger = 1
    


        }//end while
        counterA = 1;
        factorialInteger = 1;
    
      }//end main