user3670893 user3670893 - 4 months ago 24
Java Question

Cannot invoke method on the array type int[]

I have a class listed as such:

public class Something {

private int foo;
private int bar;
private int [] array = new int [16];

public Something()
{
foo = 0;
bar = 0;
for (int i =0; i < array.length; i++)
{
array[i] = 0;
}
}


I want to break the array iteration into a separate method so I can reuse or re-invoke it throughout my program something like this:

public void arrayItteration(){
for (int i =0; i < array.length; i++)
{
array[i] = 0;
}
}


Then I want to call it inside my public method such as:

public Something()
{
foo = 0;
bar = 0;
int [] arrayOp = array.arrayItteration();
}


Ive tried the solution here: Cannot invoke my method on the array type int[] by adding
this.
but its still not working. I have my setters and getters for all available variables. Im sure theres an easy fix to this but please let me know if theres a way around it.

Thank you

Answer

You are mixing a few wrong things here:

  1. calling a custom method arrayItteration on a regular int[]-array
  2. trying to assign the void return value to anything
  3. you needlessly try to get a reference to the some class member

Simplest fix:

  1. simply call the method
  2. do not assign the return value
  3. do not introduce a new local variable

That yields:

public Something() {
    foo = 0;
    bar = 0;
    arrayItteration();
}
Comments