简体   繁体   English

在java中为char数组子列表赋值

[英]Assigning values to char array sublists in java

How could I assign a int value to each of the sublists in the multidimensional char array如何为多维字符数组中的每个子列表分配一个 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;
    }

As mentioned in the comment, if you are flexible in storing char[][] letters in Map, one of the ways could be -正如评论中提到的,如果您可以灵活地在 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;
    }

Other way round, you can store the letters as key and their point value as value in map like this -反过来,您可以将字母存储为键,并将它们的点值存储为地图中的值,如下所示 -

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

then you logic will be simplified a lot -那么你的逻辑就会简化很多——

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

and you are done.你就完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM