Java if语句检查 [英] Java if statement checking
问题描述
我正在制作一个糟糕的2D重拍我的世界作为java中的一个类项目,我有一个制作工作台的东西(或者其他任何东西)我有一个if语句来检查你是否有一块木头在左上方,在其他3个中没有任何东西,或者如果右上方有一块木头而在另外3个中没有任何东西,依此类推......
I'm making a terrible 2D remake of Minecraft as a class project in java, and I have a crafting bench thing (or whatever it's called) and I have an if statement that checks if you have one piece of wood in the top left and nothing in the other 3, or if you have one piece of wood in the top right and nothing in the other 3, and so on...
我正在使用的以下if语句似乎让你在同一时间在多个插槽中有一个木头块,但仍然可以让你获得木板块。( id1
- id4
代表制作工作台的插槽)2x2制作工作台 Tile.wood
是一个木块, Tile.blank
基本上是空块或什么也不是。
The following if statement which I'm using seems to let you have a "wood" block in multiple slots at the same time and still lets you get the "plank" block. (id1
- id4
represent the crafting bench slots) 2x2 crafting bench Tile.wood
is a wood block, Tile.blank
is basically a null block or nothing.
//this if statement is what I need to change maybe?
if ((id1.id == Tile.wood && id2.id == Tile.blank
&& id3.id == Tile.blank && id4.id == Tile.blank) ||
(id1.id == Tile.blank && id2.id == Tile.wood
&& id3.id == Tile.blank && id4.id == Tile.blank) ||
(id1.id == Tile.blank && id2.id == Tile.blank
&& id3.id == Tile.wood && id4.id == Tile.blank) ||
(id1.id == Tile.blank && id2.id == Tile.blank
&& id3.id == Tile.blank && id4.id == Tile.wood)) {
//this code I don't need to change, it works fine
Inventory.inv_result.id = Tile.plank;
Inventory.inv_result.blockNum += 4;
System.out.println("You can have 4 planks");
}
所以再一次你应该只允许在一个地方有一个街区一次,否则它什么都不做。
So once again you should only be allowed to have one block in one place at one time, otherwise it will do nothing.
我怎样才能解决这个问题所以如果只有一个木头块,我只会得到木板块四个插槽?
How can I fix it so I only get the "plank" block if there is only a single "wood" block in one of the four slots?
推荐答案
if条件看起来不整齐但会完美无缺。但是,您可以对其进行模块化以便更好地理解和调试。
The if-condition looks untidy but will work perfectly fine. However, you can modularize it for better understanding & debugging.
为您创建一些实用工具方法,如下所示:
Create few utility methods to do jobs for you, as below:
boolean isWood(<id object>) {
if(Tile.wood.equals(<id object>))
return true;
else
return false;
}
boolean isBlank(<id object>) {
if(Tile.blank.equals(<id object>))
return true;
else
return false;
}
void doProcess(){
Inventory.inv_result.id = Tile.plank;
Inventory.inv_result.blockNum += 4;
System.out.println("You can have 4 planks");
}
然后重写你的if条件,如下所示
Then re-write your if-condition like below
if(isWood(id1.id) && isBlank(id2.id) && isBlank(id3.id) && isBlank(id4.id))
doProcess();
else if(isWood(id2.id) && isBlank(id1.id) && isBlank(id3.id) && isBlank(id4.id))
doProcess();
else if(isWood(id3.id) && isBlank(id2.id) && isBlank(id1.id) && isBlank(id4.id))
doProcess();
else if(isWood(id4.id) && isBlank(id2.id) && isBlank(id3.id) && isBlank(id1.id))
doProcess();
Shishir
这篇关于Java if语句检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!