在Java中将值分配给char数组子列表

时间:2019-01-25 05:00:29

标签: java arrays

如何为多维char数组中的每个子列表分配一个int值

    public int getScore(String Input)
    {
        /* Initial score is 0 but then will increase based on letter value*/
        int totalScore = 0;
        /* Takes countryInput value and converts it to a character array*/
        char[] word = Input.toCharArray();

        /* Grouped letters together based on point values */
       char[][] letters = {{'a','e','i','o','u','l','n','s','t','r'},{'d','g'},
           {'b','c','m','p'},{'f','h','v','w','y'},{'k'},{'j','x'},{'q','z'}};


        return totalScore;
    }

1 个答案:

答案 0 :(得分:1)

如评论中所述,如果您灵活地在Map中存储char [] []字母,则方法之一可能是-

public int getScore(String input)
    {
        /* Initial score is 0 but then will increase based on letter value*/
        int totalScore = 0;

        /* Takes countryInput value and converts it to a character array*/
        char[] word = input.toLowerCase().toCharArray();

        /* Grouped letters together based on point values */
       //char[][] letters = {{'a','e','i','o','u','l','n','s','t','r'},{'d','g'},
       //    {'b','c','m','p'},{'f','h','v','w','y'},{'k'},{'j','x'},{'q','z'}};

       /*Store letters grouping in map with their value as Key*/
       Map<Integer, List<Character>> letters =  new HashMap<>();
       letters.put(1, Arrays.asList('a','e','i','o','u','l','n','s','t','r'));
       letters.put(2, Arrays.asList('d','g'));
       letters.put(3, Arrays.asList('b','c','m','p'));
       letters.put(4, Arrays.asList('f','h','v','w','y'));
       letters.put(5, Arrays.asList('k'));
       letters.put(6, Arrays.asList('j','x'));
       letters.put(7, Arrays.asList('q','z'));

       for(char ch: word) {
           for(Entry<Integer, List<Character>> entrySet : letters.entrySet()) {
               if(entrySet.getValue().contains(ch)) {
                   totalScore += entrySet.getKey();
                   break;
               }
           }
       }

       return totalScore;
    }

反之,您可以像这样将字母存储为键,并将其点值存储为地图中的值-

Map<Character, Integer> map = new HashMap<>();
map.put('a',1);
.
.
.
map.put('z',7);

那么您的逻辑将大大简化-

for(char ch: word) {
    totalScore += map.get(char);
}

您完成了。