I'm trying to make a void to check if something is true, and if something is, make a string say something depending on what was true
public void sortingFamilyName(Player player) {
if (player.Zamorak == true) {
godFamily = "Zamorak";
}
if (player.Saradomin == true) {
godFamily = "Saradomin";
}
if (player.Guthix == true) {
godFamily = "Guthix";
}
if (player.Zaros == true) {
godFamily = "Zaros";开发者_运维知识库
}
if (player.Seren == true) {
godFamily = "Seren";
}
if (player.Bandos == true) {
godFamily = "Bandos";
}
if (player.Armadyl == true) {
godFamily = "Armadyl";
}
}
Theres smallish trouble. It doesn't work. How can I make it so, if Armadyl is true, godFamily would be "Armadyl"?
First, it is my opinion that you should really be using Enum
s instead of boolean
variables to determine the family of a given player. Then, you would compare your Enum
variable player
with Player.Armady1
, like so:
if (player == Player.Armadyl) {
godFamily = "Armadyl";
}
Also, you should use else if
, so that when you match a family name, you don't do any more comparisons.
Moreover, you can also define the toString
method in your Enum
, thus avoiding the if chain
that you have:
public enum Player {
ZAMORAK { public String toString() { return "Zamorak"; } },
ARMADY { public String toString() { return "Armady1"; } }
}
Now, if you want to get the description of a given player, you just invoke its toString
method.
While I've not seen all of your code, it looks like you might benefit from using an enum for family name rather than a bunch of boolean fields. You'd just have a Player.familyName field (or whatever you want to call it) with the type of the FAMILY_NAME enum you define.
where does that boolean come from? i would change that, so instead of setting the boolean to true directliy write the string player.godFamily and check that.
It looks like you should be using else if
instead of if
for all but the first one. In your code if more than one is true
then godFamily will be set to the last true one.
精彩评论