在 C# 或 Java 中基于 C# 或 Java 中的多个分数进行字符串查找的好方法
本文关键字:Java 字符串 查找 方法 | 更新日期: 2023-09-27 18:36:44
我正在寻找一种基于 C# 或 Java 中的各种分数返回字符串的好方法。例如,假设我有以下分数由双打表示:
double scoreIQ = 4.0;
double scoreStrength 2.0;
double scorePatience 9.0;
假设我想根据上述分数返回一个字符串。以清晰、易于理解的方式构建它的好方法是什么,不像下面这样:
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
}
立即想到的事情是删除硬编码字符串并使用关键字/短语的字符串创建器,根据分数创建句子。我不想使用嵌套的 if 语句,因为如果我想超过 3 分怎么办?排列将呈指数级增长。
以上只是一个例子,我正在寻找一些可以处理这种情况的结构。显然,这是错误的做法。我正在寻找一个人来引导我朝着正确的方向前进。谢谢!
如果您有一系列是否值,一种方法是位掩码,其中每个位表示一个是否值。
例如,让位 0(从右到左编号的位,从 0 开始)对于 scoreIQ>= 4.0 为真,否则为 0。
让位 1 对于 scoreStrength>= 2.0 为真,否则为 0。
让位 2 对于 scorePatience>= 9.0 为真,否则为 0。
因此,如果您想知道某人的智商是否很高并且非常有耐心,但并不强壮,您可以使用位掩码为 101
的 AND
运算符来执行此测试。
其他例子:
000 - person has poor IQ, is not strong, and is not patient
001 - person has good IQ, is not strong, and is not patient
011 - person has good IQ, is strong, and is not patient
110 - person has poor IQ, is strong, and is patient
添加新条件时,您只需对新条件使用另一个位。
因此,要构建一个位掩码来测试您关心的特征,您可以执行以下操作:
// find out if person has good IQ and is patient, but not strong
int mask = 0;
mask |= (1<<0); // set bit 0 (good IQ)
mask |= (1<<2); // set bit 2 (patient)
if (personsMask & mask == mask) {
// you know the person has a good IQ and is patient, but they are `not` strong
}
在Java中,你可以使用NavigableMap(不知道C#中有类似的东西)
TreeMap<Double, String> patience = new TreeMap<Double, String>();
patience.put(0.0, "no");
patience.put(5.0, "some");
patience.put(7.5, "a lot of");
System.out.println("You have " + patience.floorEntry(6.0).getValue() + " patience!");
见 http://docs.oracle.com/javase/7/docs/api/java/util/NavigableMap.html
使用字典你可以做这样的事情......
class Program
{
static void Main(string[] args)
{
ScoreTextTranslator dec = new ScoreTextTranslator();
dec.IfAtLeast(0, "stupid");
dec.IfAtLeast(5, "average intelligence");
dec.IfAtLeast(6, "smart");
Console.WriteLine(dec.GetTextForScore(5.7f));
}
}
class ScoreTextTranslator
{
Dictionary<float, string> backing = new Dictionary<float, string>();
public void IfAtLeast(float value, string text)
{
backing.Add(value, text);
}
public string GetTextForScore(float ActualScore)
{
var scoreRange = backing.Keys.Where(a => a <= ActualScore);
if (scoreRange.Count() == 0)
throw new Exception("No valid score text exists");
else
return backing[scoreRange.Max()];
}
}