gpt4 book ai didi

java - 重构/优化代码

转载 作者:行者123 更新时间:2023-11-29 21:15:56 26 4
gpt4 key购买 nike

我已经编写了一个方法来尝试优化我的代码,因为同一个东西被调用了 3 次不同的时间,但是,重写这个方法只是为了解决类似的问题。它基本上做同样的事情,但只是根据参数更改变量。

public void checkChance(String spawnX, int chance, int value) {
if (spawnX.equals("smallX")) {
if (player.getX() > screenWidth / 2) {
if (chance > value) {
smallX = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
} else {
smallX = random.nextInt((screenWidth / 2) - 0);
}
} else {
if (chance > value) {
smallX = random.nextInt((screenWidth / 2) - 0);
} else {
smallX = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
}
}
} else if (spawnX.equals("mediumX")) {
if (player.getX() > screenWidth / 2) {
if (chance > value) {
mediumX = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
} else {
mediumX = random.nextInt((screenWidth / 2) - 0);
}
} else {
if (chance > value) {
mediumX = random.nextInt((screenWidth / 2) - 0);
} else {
mediumX = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
}
}
} else if (spawnX.equals("largeX")) {
if (player.getX() > screenWidth / 2) {
if (chance > value) {
largeX = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
} else {
largeX = random.nextInt((screenWidth / 2) - 0);
}
} else {
if (chance > value) {
largeX = random.nextInt((screenWidth / 2) - 0);
} else {
largeX = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
}
}
}

}

理想情况下,我会喜欢它,所以我只需要每个 if 正文中的部分(检查 spawnX 等于什么)并且只需更改设置的变量。我该怎么做?

最佳答案

无需深入研究有关方法签名的设计以及此代码要实现的目标[为什么要减去 0? screenWidth - (screenWidth/2) 总是简单地等于 screenWidth/2],我认为像下面这样的东西会更清晰,减少重复:

public void checkChance(final String spawnX, final int chance, final int value) {
int intermediary;

if (player.getX() > screenWidth / 2) {
if (chance > value) {
intermediary = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
} else {
intermediary = random.nextInt((screenWidth / 2) - 0);
}
} else {
if (chance > value) {
intermediary = random.nextInt((screenWidth / 2) - 0);
} else {
intermediary = random.nextInt(screenWidth - (screenWidth / 2)) + (screenWidth / 2);
}
}

if (spawnX.equals("smallX")) {
smallX = intermediary;
} else if (spawnX.equals("mediumX")) {
mediumX = intermediary;
} else if (spawnX.equals("largeX")) {
largeX = intermediary;
}
}

关于java - 重构/优化代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21458654/

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