1

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.

3
  • Look at how you defined your variable CordArray in Enemy and look at the arg list for returnCords. You cannot pass an ArrayList when it is expecting an int array. Commented May 9, 2015 at 23:35
  • ChordArray is a local variable in your constructor and nothing else referenced it so it ceased to exist as soon as the constructor exited. Commented May 9, 2015 at 23:35
  • 1
    Typical rep-w***e bait question Commented May 9, 2015 at 23:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

There are more problems with his code than the two you listed
yes, visibility of CordsArray, the others are consequence of the two I mentioned.
1

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;
    }
}

Comments

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.