Java Return method with math operators and an array

I need to create a function that returns dividors of x/2, put them into a array and returns this array. "x" is a input from a user from diffrent method.

public static int[] findDividers(int[] x) {


    int[] array = new int[x/2];
    for(int i=1; i <= array.length; i++) {
        // int c = x/i;
        if (x%i == 0) {
            array[i] = i;   
            System.out.println(i);

        }
    return array;

    }

I keep getting error:

"the operator / and % is undefined for the argument type(s) int[], int"

Any suggestions?

2 answers

  • answered 2018-10-11 20:09 mettleap

    Your function should be fine if you just modify your argument to the findDividers method. It should be as follows:

    //Will return dividers of x, not x/2
    public static int[] findDividers(int x) { //not int[] x
    //if x is of type int[] i.e an array, it makes no sense to
    //use the '/' and '%' operators on it. That's why the compiler was
    //complaining on your code
    
    int[] array = new int[x/2];
    for(int i=1; i <= array.length; i++) {
        // int c = x/i;
        if (x%i == 0) {
            array[i-1] = i;   
            System.out.println(i);
    
        }
    
    }
    return array;
    }
    

  • answered 2018-10-11 20:54 Joakim Danielson

    Here is my suggestion, it will return an array containing the dividers only, so findDividers(10) will return the array [1,2,5]

    public static int[] findDividers(int x) {
        int roof = x / 2;
        int[] values = new int[roof];
    
        int test = 1;
        int count = 0;
        while (test <= roof) {
            if (x % test == 0) {
                values[count] = test;
                count++;
            }
            test++;           
        }
        return Arrays.copyOf(values, count);
    }