import java.util.Scanner;
public class Test{
public static int[] calculateFactors(int n){
int[] array = new int[n];
for(int i = 0; i<=n;i++){
if(n%i==0){
return array[i];
}
}
}
public static void main(String[] args){
System.out.println("Please enter the number you want to find the factors for:");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(calculateFactors(n));
}
}
I don’t understand why I get an error. I am trying to write a code where a user inputs a number and the program returns all the factors of this number.
Could anyone please tell me why when I am not being able to return the array with corresponding i factors.
Thank you
Look at your code (whitespace added for clarity):
There are two problems:
int, but your method declares that it returns anint[]nis -1? It will never go through the loop, so it will never return. More generally, the compiler will assume that (almost) anyifcondition may be false.Now, as to how to fix it – given the method name, it sounds like you really do want to return all the factors… so you shouldn’t return as soon as you’ve found the first one. I’d collect the factors in a
List<Integer>instead of in an array. Convert thereturnstatement to anaddcall, and then return at the end of the loop. Oh, and you probably want to start the loop withias 1 rather than 0…All of this is specific to this particular problem though. More generally, you should look at the errors that the compiler’s giving you. They should give you all the information you need to work this out for yourself. Now that you do understand the problem, read the messages again and try to work out what stopped you from understanding it before. Could you have worked it out yourself, or were you missing some important concept?