首页 > 解决方案 > Java中的异构数组类型转换

问题描述

我是 Java 新手,目前正在处理实现数组的代码。

Scanner sc= new Scanner(System.in);
String str=sc.nextLine();
int count[]= new int[25];
int len = str.length(); 

// Initialize count array index 
for (int i = 0; i < len; i++) 
    {count[str.charAt(i)]++; } //This line is the issue.

我想知道 charAt() 是否返回 char 值,那么 count[] (整数数组)如何存储它,如果可以,那么如何存储。我已经从这个链接中提取了源代码在此处输入链接描述

谢谢你。

标签: javaarrays

解决方案


地图不是数组。数组的数字索引从 0 开始,您尝试使用字符值作为索引...

所以你有2条可能的路径:

  • 使用Map<char, int>将由字符本机索引的 a - 但您必须在第一次遇到字符时设置 1 值。优点:接受非字母字符,缺点:更复杂的处理
  • 坚持使用数组并使用从 char 到 [0-26[ 范围内的数字的转换。是一个很好的星点,因为它映射了 [10-36[ 范围内的所有字母 - 顺便说一下,您需要一个大小为26而不是 25Character.getNumericValue的数组

你的代码可能变成:

Scanner sc= new Scanner(System.in);
String str=sc.nextLine();
int count[]= new int[26];
int len = str.length(); 

// Initialize count array index 
for (int i = 0; i < len; i++) {
    val = Character.getNumericValue(str.charAt(i)) - 10;
    if (val >= 0) {  // ok we have an alpha character
        count[val]++;
    } 
}

推荐阅读