I am having trouble with my code. I am trying to make a prime factor program, and I want to remove duplicates. However, they always give me an error when I run the following code, and I am confused on why:
public static void primeFactors(int n) {
// Create array to filter out duplicates
List<Integer> primeFactorList = Arrays.asList();
// Start timer to calculate how long the program takes
long startTime= System.nanoTime();
// Print the number of 2s that divide n
System.out.print("The prime factor(s) of that number:\n");
// The following is a while loop running when the number is even
while (n % 2 == 0) {
primeFactorList.add(2);
n /= 2;
}
// n is now odd, as the even while loop is over.
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i += 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
primeFactorList.add(i);
n /= i;
}
}
// This condition is to handle the case when 'n' is a prime number greater than 2
if (n > 2) {
primeFactorList.add(n);
}
System.out.print(primeFactorList.stream().distinct().collect(Collectors.toList()));
float endTime= System.nanoTime();
float totalTime= endTime -startTime;
System.out.print("\nThis program took " + (totalTime/1000000 + " milliseconds to run"));
}
public static void main(String[] args)
{
System.out.println("This is a prime factor calculator. Please enter a number: ");
Scanner intN = new Scanner(System.in);
int nValue = intN.nextInt();
if (nValue >= 0){
int n = nValue;
primeFactors(n);
} else {
System.out.println("Your value is negative, please restart the program and enter a positive integer");
}
}
The console errors go as followed:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.amitaltman.firstproject.TestingStuff.primeFactors(TestingStuff.java:32)
at com.amitaltman.firstproject.TestingStuff.main(TestingStuff.java:54)
Arrays.asList();returns a fixed-size list. You can't add to it.List<Integer> primeFactorList = Arrays.asList();beList<Integer> primeFactorList = new ArrayList<>();. That should do it, you're using an empty list in that line anyway.