我有以下代码根据Scrabble评分规则对用户输入的字符串评分:

import java.util.Scanner;

public class ScrabbleScorer {

    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter string: ");
        String str = sc.nextLine();
        int score = computeScore (str);
        System.out.println ("The score for '" + str + "' is: " + score);
        sc.close();
    }

    public static int computeScore (String str) {
        str = str.toUpperCase();
        int score = 0;
        for(int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            switch(ch){
            case 'A': score = score + 1;break;
            case 'B': score = score + 3;break;
            case 'C': score = score + 3;break;
            case 'D': score = score + 2;break;
            case 'E': score = score + 1;break;
            case 'F': score = score + 4;break;
            case 'G': score = score + 2;break;
            case 'H': score = score + 4;break;
            case 'I': score = score + 1;break;
            case 'J': score = score + 8;break;
            case 'K': score = score + 5;break;
            case 'L': score = score + 1;break;
            case 'M': score = score + 3;break;
            case 'N': score = score + 1;break;
            case 'O': score = score + 1;break;
            case 'P': score = score + 3;break;
            case 'Q': score = score + 10;break;
            case 'R': score = score + 1;break;
            case 'S': score = score + 1;break;
            case 'T': score = score + 1;break;
            case 'U': score = score + 1;break;
            case 'V': score = score + 4;break;
            case 'W': score = score + 4;break;
            case 'X': score = score + 8;break;
            case 'Y': score = score + 4;break;
            case 'Z': score = score + 10;break;
            default : score = score;
            }

        }
        return score;
    }


}


我想知道是否有一种方法可以将switch包装到loop中,从而不必手工将其写出26次。谢谢

最佳答案

我认为您可以使用其他更清洁的方法。

您可以使用HashMap<Character, Integer>存储字符点组合。然后,您只需遍历字符串并增加分数:

HashMap<Character, Integer> pointScheme = new HashMap<>();
pointScheme.put('A', 1);
...
str = str.toUpper();
for(int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            score += pointScheme.get(ch);
}


这将使代码更整洁,也更易于维护。

09-09 21:17