我编写了一个方法来尝试和优化我的代码,因为相同的东西被调用了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等于什么),只需要更改哪个变量get的集合。我该怎么做?
发布于 2014-01-30 14:19:51
对于方法签名和这段代码实现的目标(为什么它要减去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;
}
}发布于 2014-01-30 14:12:07
在开始时,您可以这样做(伪代码)。
TYPE tmpX = (conditionSmall) ? smallX: ((conditionMedium)? medium : largeX);然后,只需更改为tmpX即可。因为Java变量(原语除外)实际上是指向对象的指针,所以您的tmpX将指向您希望修改的对象。
https://stackoverflow.com/questions/21458654
复制相似问题