I'm trying to pass an individual elements of CordsArray from the public class Enemy() to the main.
我试图将CordsArray的各个元素从公共类Enemy()传递给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:
我想通过在main中调用returnCords将CordArray的元素输出到控制台:
System.out.println(returnCords(CordArray, 0));
But a 'CordArray cannot be resolved to a variable' error appears. Apologies for bad English.
但是出现'CordArray无法解析变量'错误。抱歉英语不好。
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
问题是: - 变量名称应以小写字母开头,-lists可以包含单个对象/值,您试图在一个索引处存储两个
Create Coords object instead:
改为创建Coords对象:
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.
希望能帮助到你。
#2
try using point and a global arraylist with a get function
尝试使用point和带有get函数的全局arraylist
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;
}
}
#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
问题是: - 变量名称应以小写字母开头,-lists可以包含单个对象/值,您试图在一个索引处存储两个
Create Coords object instead:
改为创建Coords对象:
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.
希望能帮助到你。
#2
try using point and a global arraylist with a get function
尝试使用point和带有get函数的全局arraylist
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;
}
}