The title is a bit unclear I guess so I will try to explain my problem as detailed as possible.
Lets say I am writing a program for the popular game Rock, Paper, Scissors and I want to determine who won. I could achieve this by the following code:
if (computer_choice.equals(player_choice)) {
return "Draw";
} else if (computer_choice.equals("rock") && player_choice.equals("scissors")) {
return "Computer wins: " + computer_choice + " win against " + player_choice;
} else if (computer_choice.equals("rock") && player_choice.equals("paper")) {
return "Player wins: " + player_choice + " win against " + computer_choice;
} else if (computer_choice.equals("paper") && player_choice.equals("rock")) {
return "Computer wins: " + computer_choice + " win against " + player_choice;
} else if (computer_choice.equals("paper") && player_choice.equals("scissors")) {
return "Player wins: " + player_choice + " win against " + computer_choice;
} else if (computer_choice.equals("scissors") && player_choice.equals("paper")) {
return "Computer wins: " + computer_choice + " win against " + player_choice;
} else if (computer_choice.equals("scissors") && player_choice.equals("rock")) {
return "Player wins: " + player_choice + " win against " + computer_choice;
} else
{
return "Error";
}
}
Thats just 3 different options the computer and the player can choose but I think thats still a acceptably amount of code. But lets say I want to improve the program with more variations:
That would be a huge block of code if I go with the if-else statement and I think it would be very confusing by looking at the code. I thought about to solve this with a switch case but I think it would save me just some lines of code and wouldnt help that much.
So my question is, what is a better/the best way to handle that many different options?
Thanks in advance

Aucun commentaire:
Enregistrer un commentaire