0

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

1

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

gahhh....knew it would be that easy. Thanks I come from a Ruby background im used to assigning a reference to everything. Much appreciated.
@user3670893 you could create a method, that returns a new initialized array and assign that return value to array. But if your method is void you cannot even assign the return value to anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.