Skip to content
Advertisement

Storing a temporary value of a constantly changing variable

I would like to know, is it possible to store a temporary value of a variable before it switches to another one?

Following is the code snippet:

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int input = Integer.parseInt(scanner.nextLine());
        String input1 = String.valueOf(input);
        int counter = 1;

        for (int i = input1.length() - 1; i >= 0 ; i--) {
            char charValueOfI = input1.charAt(i);
            String StringValueofI = String.valueOf(charValueOfI);
            int intValueofI = Integer.parseInt(StringValueofI);
            counter = 1;
    
            for (int j = intValueofI; j >0 ; j--) {
                counter = counter * j; // if input = 145, first value saved under counter will be 120, can that value of 120 be saved somewhere, before counter changes back to 1 under the first for loop

            }
        }
    }

Advertisement

Answer

You need to have a sum variable before the for cycles, and in the first for, after the second, have the sum add the counter.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement