java - 字符的出现
问题描述
我试图忽略不在字符串字母表中的字符,但由于某种原因 eclipse 抱怨说变量 i 无法解决
这是我的代码:
import java.util.Scanner;
公共类OccurenceOfCaracters {
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str)
{
// Create array to keep the count of individual
// characters and initialize the array as 0
int count[] = new int[ASCII_SIZE];
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int charCheck;
// Construct character count array from the input
// string.
int len = str.length();
for (int i=0; i<len; i++)
charCheck = alphabet.indexOf(str.charAt(i));
if(charCheck != -1) {
count[str.charAt(i)]++; //Problem occurs here
}
int max = -1; // Initialize max count
char result = ' '; // Initialize result
// Traversing through the string and maintaining
// the count of each character
for (int i = 0; i < len; i++) {
if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}
return result;
}
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("Enter your Text: ");
String str = sc.nextLine();
str = str.replaceAll("\\s","").toLowerCase();
System.out.println("Max. character is " +
getMaxOccuringChar(str));
}
}
解决方案
问题在于循环。这来自您的代码。请注意i
for 循环是本地的,但您没有使用 {},因此稍后使用它来帮助索引时不会看到count
for (int i = 0; i < len; i++)
charCheck = alphabet.indexOf(str.charAt(i));
if (charCheck != -1) {
count[str.charAt(i)]++; // Problem occurs here
}
推荐阅读
- javascript - 开始时没有数据时的动态 Highstock 图表
- amazon-web-services - 转换速度模板时出错
- python - 哪种数据结构最好考虑插入/访问以存储不同单元的时间戳?(数据非常大)
- sql - 使用 SSD 时我应该在 PostgreSQL 上禁用位图扫描吗?
- css - 如何使用 PostCSS 在 Vue 中导入全局 CSS?
- android - 在 android studio 中出现以下错误:程序类型已存在:com.google.api.AuthProto
- javascript - 使用 mongoose 在 expressj 中验证 OTP
- javascript - Angular 5 UI 和 node.js 服务器使用护照包进行谷歌 OAuth 登录的 CORS 问题
- android - 将 Scrollview 隐藏在 Imageview 后面,反之亦然
- android - 如何在 Google Maps API 中调整地点的搜索半径?