- 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; }
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){
// ...
}
}
+ 1
Hello Denise,
Thanks for your response
+ 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
+ 1
Deepak Sandha
to print Arrays:
Array.toString() and for multidimenaional arrays Arrays.deepToString().
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?
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;
}
}
0
Thank u
Zemiak and Denise
now I got it