cvandal
cvandal

Reputation: 794

Processing an array from a class in another class

I'm having difficulty processing an array of numbers from a class file (Scores.java) within a separate class file (ProcessScores.java).

Adding Scores.main(); within the main void of ProcessScores.java does print the array but my attempts to work with the output have failed. For instance, int[] numbers = Scores.main(); throws the error "Incompatible Types. Required: int[], Found: void". I understand that I'm calling the main void from the Scores class so my question is...

How can I get the output from the Scores class into the ProcessScores class in a way that I can work with it?

Upvotes: 0

Views: 113

Answers (2)

tvervack
tvervack

Reputation: 81

You have 1 project with 2 classes which each contain a main? A project should only have 1 main class. Try something like this:

public class A {
    public static void main(String[] args) {
        B b = new B();
        int[] array = b.getArray();
        // Do something with array
        b.setArray(array);
    }
}

public class B {
    private int[] array;
    public B(){
        array = {0,1,2,3,4}; // Dummy data
    }

    public int[] getArray(){
        return array;
    }

    public void setArray(int[] array){
        this.array = array;
    }
}

Upvotes: 1

Leo
Leo

Reputation: 6570

the main() method is void (does not return anything) and since it's static, you can't use it to return the results. You could try writing other static method that returns something instead.

Try creating another public static method that returns int[] and use it instead.

For example

public static int[] mymethod(){
  ...
}

And call it like

int[] result = Scores.mymethod();

Upvotes: 0

Related Questions