- 1

Method not returning the array. Pls suggest the proper solution.

//method to find factors of a number public static int[] factors(int x) { int i,rem=1,count=0,j=0; for(i=1;i<=x;i++) //this loop counts the number of factors { rem=x%i; if(rem==0) count=count+1; } //System.out.println(count); int[] arr = new int[count]; for(i=1;i<=x;i++) //loop to assign values to array { rem=x%i; if(rem==0) { arr[j]=i; //System.out.println(arr[j]); j=j+1; } } return arr; }

1st May 2020, 6:09 PM
Deepak Sandha
Deepak Sandha - avatar
7 Respuestas
+ 3
it works, try: import java.util.Arrays; public class Program { public static void main(String[] args) { int[] f = factors(10); System.out.println(Arrays.toString(f) ); } //method to find factors of a number public static int[] factors(int x){ // ... } }
1st May 2020, 7:59 PM
zemiak
+ 1
Hello Denise, Thanks for your response
2nd May 2020, 3:26 AM
Deepak Sandha
Deepak Sandha - avatar
+ 1
The problem is the way how you try to print the result array System.out.println(factors(10)); you get then something like [I@4617c264
2nd May 2020, 7:26 AM
zemiak
+ 1
Deepak Sandha to print Arrays: Array.toString() and for multidimenaional arrays Arrays.deepToString().
2nd May 2020, 10:59 AM
Denise Roßberg
Denise Roßberg - avatar
0
Hello Deepak Sandha Can you explain your problem? Does the method not return the array or not a correct array? in your main: int[] arr = factors(5); What happens? What would be the expected output?
1st May 2020, 6:35 PM
Denise Roßberg
Denise Roßberg - avatar
0
/*Output should be factors of 10 i. e. 1 2 5 10*/ //but output is something else public class Program { public static void main(String[] args) { System.out.println(factors(10)); } //method to find factors of a number public static int[] factors(int x) { int i,rem=1,count=0,j=0; for(i=1;i<=x;i++) //this loop counts the number of factors { rem=x%i; if(rem==0) count=count+1; } //System.out.println(count); int[] arr = new int[count]; for(i=1;i<=x;i++) //loop to assign values to array { rem=x%i; if(rem==0) { arr[j]=i; //System.out.println(arr[j]); j=j+1; } } return arr; } }
2nd May 2020, 3:28 AM
Deepak Sandha
Deepak Sandha - avatar
0
Thank u Zemiak and Denise now I got it
2nd May 2020, 5:57 PM
Deepak Sandha
Deepak Sandha - avatar