gpt4 book ai didi

java - 通过java数组访问float变量

转载 作者:行者123 更新时间:2023-12-01 23:37:57 26 4
gpt4 key购买 nike

我是Java新手,我一直在编写一个程序来练习。贝娄是该程序的有问题的类。我试图通过数组操作浮点变量,但我似乎无法以这种方式影响它们(例如 array[i] = 1),也无法获取它们的值(始终为 0.0),但可以直接访问它们(例如,variable = 1) )有效。谁能告诉我我做错了什么?谢谢。

public class Statistics {
private float switchWin, switchLose, stayWin, stayLose, gamesPlayed, switchWinP, switchLoseP, stayWinP, stayLoseP;
private float statisticsArray[] = {switchWin, switchLose, stayWin, stayLose, gamesPlayed, switchWinP, switchLoseP, stayWinP, stayLoseP};

public void setSwitchWin() {
switchWin++;
}

public void setSwitchLose() {
switchLose++;
}

public void setStayWin() {
stayWin++;
}

public void setStayLose() {
stayLose++;
}

public void setGamesPlayed() {
gamesPlayed++;
}

public String getSwitchWinPercentage() {
return Float.toString(switchWinP = (switchWin/gamesPlayed)*100);
}

public String getSwitchLosePercentage() {
return Float.toString(switchLoseP = (switchLose/gamesPlayed)*100);
}

public String getStayWinPercentage() {
return Float.toString(stayWinP = (stayWin/gamesPlayed)*100);
}

public String getStayLosePercentage() {
return Float.toString(stayLoseP = (stayLose/gamesPlayed)*100);
}

public String getGamesPlayed() {
return Integer.toString((int) gamesPlayed);
}

public void reset() {
for(int i=0; i<statisticsArray.length; i++) {
System.out.println(statisticsArray[i]);
statisticsArray[i]=0.0f;
System.out.println(statisticsArray[i]);
}
}
}

最佳答案

在 Java 中,基元(floatint 等)不能像对象一样被引用,也不能通过引用传递。

statisticsArray 不保存对初始化它的变量的引用,它会在您初始化时在数组内创建变量的副本执行此调用。

private float statisticsArray[] = {switchWin, switchLose, stayWin, [..]};

statisticsArray 现在保存 switchWin 等变量的默认值 (0)。

关于java - 通过java数组访问float变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18370641/

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