java - 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[] (整数数组)如何存储它,如果可以,那么如何存储。我已经从这个链接中提取了源代码在此处输入链接描述
谢谢你。
解决方案
地图不是数组。数组的数字索引从 0 开始,您尝试使用字符值作为索引...
所以你有2条可能的路径:
- 使用
Map<char, int>
将由字符本机索引的 a - 但您必须在第一次遇到字符时设置 1 值。优点:接受非字母字符,缺点:更复杂的处理 - 坚持使用数组并使用从 char 到 [0-26[ 范围内的数字的转换。是一个很好的星点,因为它映射了 [10-36[ 范围内的所有字母 - 顺便说一下,您需要一个大小为26而不是 25
Character.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]++;
}
}
推荐阅读
- python - Gimp 自动化(Scripz Fu/Python Fu)
- javascript - Laravel 7 jQuery UI datepicker: Uncaught TypeError: $(...).datepicker is not a function
- javascript - JavaScript 从另一个对象创建对象
- java - Selenium WebDriver 无耻地返回不正确的 WebElement 高度
- python - Django Listview FormMixin
- ansible - ansible playbook 执行并且没有显示错误,但没有在主机上执行预期的操作
- php - 我如何在不重复自己的情况下更好地编写此语句,它需要使用简单的 html dom 的值
- android - Android Studio - 加载小部件时出现问题(切换/切换)
- javascript - 如何将数据从 javascript 发送到 python 烧瓶后端?
- java - java - 如何通过java中的selenium在弹出框中发送用户名和密码?