我试图忽略不在字符串字母表中的字符,但由于某种原因 eclipse 提示,变量 i 无法解析
这是我的代码:
import java.util.Scanner;
公共(public)类 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
}
关于java - 字符的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037238/