Home > Software engineering >  Finding Multiple of 3 in a Array Method and returning it
Finding Multiple of 3 in a Array Method and returning it

Time:05-18

I'm currently trying to find all the multiple values of three in an array. I know hot to do it without using a method, but when I'm trying to invoke the method and retrieve the returned array, it gives me errors and won't work.

public class Scratchpad extends ConsoleProgram
{
    public void run()
    {
        int[] test = {4, 7, 9, 7, 12};
        
        findMultipleOfThree testArr = new findMultipleOfThree[int[] test];
        
        System.out.println(testArr);
    }
    // Copy and paste your Unit Test method here
    
    public int findMultipleOfThree(int[] arr)
    {
        int length = arr.length;
        int[] result = new int[length];
    
        for(int i = 0; i < arr.length; i  )
        {
        
            if(arr[i] % 3 == 0)
            {
                result[i] = arr[I];
            }
        }
        return result;
    }
}

CodePudding user response:

There are a few problems in your code. I think that in your second instruction of the run method, you were attempting to invoke the findMultipleOfThree method you defined below.

To invoke a method, you simply need to type its name and pass the parameters it's expecting. In your case, the test array to find the elements divisible by 3. Plus, you also need to declare a second array result in order to store the returned array from your method with only the element divisible by 3.

Ultimately, in your findMultipleOfThree method there was a small typo where you referred to the i variable as I. Java is case-sensitive, so it distinguishes between lower and upper letters.

I think this is what you were trying to write.

public class Scratchpad extends ConsoleProgram {
    public void run() {
        int[] test = {4, 7, 9, 7, 12};
        int[] result = findMultipleOfThree(test);
        System.out.println(Arrays.toString(result));
    }

    public static int[] findMultipleOfThree(int[] arr) {
        int length = arr.length;
        int[] result = new int[length];
        for (int i = 0; i < arr.length; i  ) {
            if (arr[i] % 3 == 0) {
                result[i] = arr[i];
            }
        }
        return result;
    }
}

CodePudding user response:

It looks like you're mixing up methods and classes. You can't declare an instance of a method, and they aren't types you can use for the type of a variable. If you want to call the method, you'd want to use something like int result = findMultipleOfThree(test); and print the result of that with System.out.println(result); Hope this helps!

  • Related