Octarine
Octarine

Reputation: 21

How to return Array List element from method

I'm trying to pass an individual elements of CordsArray from the public class Enemy() to the main.

public class Enemy {

//constructor
public Enemy()
{
    //*create array of coordinates
    ArrayList<Integer> CordArray = new ArrayList<Integer>();

    CordArray.add(0,2);
    CordArray.add(1,5);
    CordArray.add(2,8);
    CordArray.add(3,10);
}

public static int returnCords(int[] CordArray, int index) 
{   
    return CordArray[index]; 
}

I'm wanting to output elements of the CordArray to the console by calling returnCords in main:

System.out.println(returnCords(CordArray, 0));

But a 'CordArray cannot be resolved to a variable' error appears. Apologies for bad English.

Upvotes: 1

Views: 4431

Answers (2)

DoubleMa
DoubleMa

Reputation: 368

try using point and a global arraylist with a get function

import java.awt.Point;
import java.util.ArrayList;

public class Enemy {

    private final ArrayList<Point> points;

    public Enemy() {
        points = new ArrayList<>();
        points.add(new Point(2, 5));
        points.add(new Point(8, 10));
    }

    public ArrayList<Point> getPoints() {
        return points;
    }

    public static void main(String[] args) {
        Enemy enemy = new Enemy();
        int index = 0;
        Point point = enemy.getPoints().get(index);
        int x = point.x;
        int y = point.y;
    }
}

Upvotes: 1

Suspended
Suspended

Reputation: 1190

The problems are:
-variable names should begin with lowercase letter,
-lists can contain single objects/values, you are trying to store two at one index

Create Coords object instead:

public class Coords{
    private int x;
    private int y;

    public Coords(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }
}

Now you can do this:

ArrayList<Coords> cordArray = new ArrayList<Coords>();

Hope it helps.

Upvotes: 1

Related Questions