gpt4 book ai didi

java - 数组和方法的问题

转载 作者:行者123 更新时间:2023-11-29 04:19:06 25 4
gpt4 key购买 nike

当我在方法中为数组赋值时,当我尝试在其他方法中使用它们时,它们变为 0。

我对 Java 编程也不是很熟悉。

这是我的代码:

    public int[] pVectorCoinOne = new int[2];
public int[] pVectorCoinTwo = new int[2];
public int[] pVectorCoinThree = new int[2];
public int[] pVectorCoinFour = new int[2];
public int[] pVectorCoinFive = new int[2];
public int[] pVectorCoinSix = new int[2];


public void setPositionVectors(){

int[] pVectorCoinOne = {lblCoinImage1.getX(), lblCoinImage1.getY()};
int[] pVectorCoinTwo = {lblCoinImage2.getX(), lblCoinImage2.getY()};
int[] pVectorCoinThree = {lblCoinImage3.getX(), lblCoinImage3.getY()};
int[] pVectorCoinFour = {lblCoinImage4.getX(), lblCoinImage4.getY()};
int[] pVectorCoinFive = {lblCoinImage5.getX(), lblCoinImage5.getY()};
int[] pVectorCoinSix = {lblCoinImage6.getX(), lblCoinImage6.getY()};

}

public void printAllToOutput(){

setPositionVectors();

System.out.println(Arrays.toString(pVectorCoinOne));
System.out.println(Arrays.toString(pVectorCoinTwo));
System.out.println(Arrays.toString(pVectorCoinThree));
System.out.println(Arrays.toString(pVectorCoinFour));
System.out.println(Arrays.toString(pVectorCoinFive));
System.out.println(Arrays.toString(pVectorCoinSix));

}

最佳答案

像这样修复:

public void setPositionVectors(){

pVectorCoinOne[0] = lblCoinImage1.getX(); //example

}

一切都与范围有关——本地与全局。而且你不能像这样直接设置数组。在java中,只能在初始化时将常量设置为数组。

喜欢:

public int[] array = {1, 2};

当你写作时

public void setPositionVectors(){

int[] pVectorCoinOne = {lblCoinImage1.getX(), lblCoinImage1.getY()};
int[] pVectorCoinTwo = {lblCoinImage2.getX(), lblCoinImage2.getY()};
int[] pVectorCoinThree = {lblCoinImage3.getX(), lblCoinImage3.getY()};
int[] pVectorCoinFour = {lblCoinImage4.getX(), lblCoinImage4.getY()};
int[] pVectorCoinFive = {lblCoinImage5.getX(), lblCoinImage5.getY()};
int[] pVectorCoinSix = {lblCoinImage6.getX(), lblCoinImage6.getY()};

}

该方法在其自身内部初始化具有相同名称的新局部变量,而不是调用您在上面声明的变量。所以方法结束时变量会消失,什么都不会改变。

关于java - 数组和方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50381593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com