I'm trying to make something that gives us the multiplicative root and the multiplicative persistence of a number.
So I made a method that gives us a list with 2 elements- the root and the persistence. So I made an empty list named answers and then added the elements in an if and while loop.
But when I then tried to print the List it gives an error.
Here's the code I made:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
long number = 123456789;
String dupeNumber=String.valueOf(number);
List<Long> answers;
if (dupeNumber.length() > 1) {
while (dupeNumber.length() > 1) {
long intNumber = Integer.parseInt(dupeNumber);
List<Long> digits = separated(intNumber);
answers = prodDigits(digits);
dupeNumber=String.valueOf(answers);
System.out.println(dupeNumber);
}
}
System.out.println(answers);
}
static List<Long> separated(long number) {
List<Long> digits = new ArrayList<>();
while (number > 0) {
digits.add((number % 10));
number -= (number % 10);
number /= 10;
}
return digits;
}
static List<Long> prodDigits(List<Long> digits) {
List<Long> answers = new ArrayList<>();
long product = 1;
long persistence = 0;
for (long i : digits) {
product *= i;
persistence += 1;
}
answers.add(product);
answers.add(persistence);
return answers;
}
}
The error and the error line is
- 18:28 java: variable answers might not have been initialized
I want the output to be like this:
If the number given is 123456789: [0, 2] as 123456789=362800 and 36280*0=0 and multiplication happened 2 times.