如何获取char的数字位置

时间:2016-10-01 17:21:51

标签: java arrays char

假设我们有一堆char:'s', 'w', 'e', 's', 't', 'h'

我们怎样才能看到我们是否通过(char)scanner.nextLine().charAt(0);输入了一个角色 数字为(1,2,3,4,5,6)的位置。例如,如果我输入w我会返回2,或者如果我输入s,我会返回14

这是我已有的代码:

   Scanner letter= new Scanner(System.in);
   System.out.print("Type a character:");
   char let= letter.nextLine().charAt(0);

   char[] word = {'s', 'w', 'a', 'g', 'w' };
   System.out.print();

1 个答案:

答案 0 :(得分:0)

你可以使用地图

简单地完成
        Map<Character,List<Integer>> map = new HashMap<Character,List<Integer>>();

然后迭代数组中的字符并将其位置添加到地图中,并使用键符号

         if(map.get(word[i]) == null)//i is the index of the character
                    map.put(word[i],new ArrayList<Integer>());
          map.get(word[i]).add(i);

然后当您插入角色时,您将获得相关列表并打印其内容