I am looking for a good way to return a string based on various scores in either C# or Java. For example, let’s say I have the following scores represented by doubles:
double scoreIQ = 4.0;
double scoreStrength 2.0;
double scorePatience 9.0;
Let’s say I wanted to return a string based on the above scores. What would be a good way to structure this in a clear, easy to understand way unlike the following:
public static string ReturnScore(double scoreIQ, double scoreStrength, double scorePatience)
{
if (scoreIQ <= 5.0)
{
if (scoreStrength <= 5.0)
{
if (scorePatience <= 5.0)
{
return "You're stupid, weak, and have no patience";
}
else if (scorePatience <= 7.5)
{
return "You're stupid, weak, and have some patience";
}
else
{
return "You're stupid, weak, and have a lot of patience";
}
}
//Continue elseif return string permutations here
}
//Continue elseif return string permutations here
}
Things that immediately come to mind would be to remove the hard-coded strings and use a string creator of keywords/phrases that creates sentences based on the scores. I don’t want to use nested if-statements because what if I wanted to go beyond 3 scores? The permutations are going to increase exponentially.
The above is just an example and what I am looking for is some structure that can handle such a scenario. Clearly, this is the wrong way of doing it. I am looking for someone to guide me in the right direction. Thanks!
If you have a series of yes no values, one way would be a bitmask, where each bit represents one of the yes no values.
For example, let bit 0 (bits numbered from right to left, starting at 0) be true for scoreIQ >= 4.0, and 0 otherwise.
Let bit 1 be true for scoreStrength >= 2.0, and 0 otherwise.
Let bit 2 be true for scorePatience >= 9.0, and 0 otherwise.
So, if you wanted to know if someone has a high IQ and is very patient, but is not strong, you could use the
ANDoperator with a bitmask of101to perform this test.Other examples:
As new criteria are added, you just use a another bit for the new criteria.
So, to build a bitmask to test the characteristics you care about, you can just do something like this: