如何创建一个代码,使字母表中的每个字母都分配给拼字游戏分数?例如,a = 1点,b = 3点,c = 3点。如果我有String" abc" String的值为7分。到目前为止我的想法是这两个数组:
private int[] Points= {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
private String Letters[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
答案 0 :(得分:1)
您可以使用HashMap
。 get()
部分将返回3. String
也可以更改为Character
的字符。
HashMap<String, Integer> map=new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 3);
map.get("b");
答案 1 :(得分:1)
我不确定你写的是哪种语言,但我可以帮助你理解一般概念。你可以使用一个对象(javascript)或dictionairy(python)或hash(ruby)并为每个字母分配一个像这样的分数值
scores = {
"a":1,
"b":3,
"c":3
}
等等,直到z 然后找到你可以做这样的事情的分数使用一个javascript示例,但它在其他语言中使用循环非常相似
var word = abc;
var score = 0;
for(i=0;i<word.length;i++){
result += scores[i]
}
答案 2 :(得分:0)
我使用的是散列图,其中键是char(字母),值是int(得分)。
答案 3 :(得分:0)
您可以拥有Map:
private static final Map<Character, Integer> letterValues = new HashMap<>();
static {
letterValues.put('a', 1);
letterValues.put('b', 3);
// ...
letterValues.put('z', 10);
}
然后制作一个方法:
public int getWordValue(String word) {
int value = 0;
for(int i = 0; i < word.length(); i++) {
value += letterValue.get(word.charAt(i));
}
return value;
}
或者,您可以使用开关来执行此操作:
public int getLetterValue(char letter) {
switch(letter) {
case 'a': return 1;
case 'b': return 3;
// ...
case 'z': return 10;
default: return 0;
}
}
答案 4 :(得分:-1)
public static void display() {
int[] points = { 1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10,
1, 1, 1, 1, 4, 4, 8, 4, 10 };
String letters[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z" };
//Holding alphabet's corresponding value in a map
Map<String, Integer> tempMap = new HashMap<String, Integer>();
for (int i = 0; i < letters.length; i++) {
tempMap.put(letters[i], points[i]);
}
//Test Data
String test = "abc";
int sum = 0;
for (int i = 0; i < test.length(); i++) {
sum += tempMap.get(test.charAt(i)+"");//making character to string
}
System.out.println(sum);
}