13 Replies Latest reply on Apr 18, 2011 11:17 AM by gimbal2

    How do I reset a variable after each iteration of a loop?

    854207
      Here is the code if you need to see it. "fact" is what I want to reset each time the method factorialN is completed. Thanks in advance.
      import java.util.Scanner;
      
      public class Factorial {
           static int fact = 1;
           static int newNum = 0;
           /**
            * @param args
            */
           public static void main(String[] args) {
                // TODO Auto-generated method stub
                char answer;
                do {
                System.out.println("What is the number? ");
                Scanner keyboard = new Scanner(System.in);
                int num = keyboard.nextInt();
                factorialN(num);
                Factorial aFactorial = new Factorial();
                System.out.println(aFactorial);
                System.out.println("Do you want to continue? y/n ");
                String answerString = keyboard.next();
                answer = answerString.charAt(0);
                }
                while (answer == 'y' || answer == 'Y');
      
           }
           
           public static void factorialN(int num) {
                while (newNum < num) {
                     newNum ++;
                     fact = fact * newNum; }
           }
           public String toString() {
                 String returnValue = "Its factorial is " + fact;
                 return returnValue;
              }
      }