这是我到目前为止得到的代码......
import java.util.Scanner;
class count{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String sent=s.nextLine();
int len = sent.length();
int arr[]=new int[len];
int count=1;
char ch[] = new char[len];
for(int i = 0; i <= len-1; i ++)
{
ch[i] = sent.charAt(i);
}
for(int j= 0;j<=len-1;j++){
for(int k=0;k<=len-1;k++){
if(ch[j]==ch[k]){
arr[j]= count++;
}
}
}
int max=arr[0];
for(int z=1;z<=len-1;z++){
if(count>max)
max=count;
}
System.out.println(max);
System.out.println("The character that appears the most number of times is " +arr[max]);
}
}
我得到计数来显示每个字符在字符串中出现的次数,我无法将它与数组中的其余元素进行比较。
出现的次数存储在数组“arr[]”中,如何找到该数组中最大的整数?另外,如何显示出现次数最多的角色?
代码的逻辑在之后不起作用,
int max=arr[0];
关于该做什么有什么想法吗?
最佳答案
String sent = "asdAdFfaedfawghke4";//s.nextLine();
int length = sent.length();
char frequentChar = ' ';
int maxLength = 0;
for (int i = 0; i < length; i++) {
char currentChar = sent.charAt(0);
sent = sent.replaceAll(currentChar + "", "");//remove all charactes from sent
if (maxLength < (length - sent.length())) {
frequentChar=currentChar;
maxLength = length - sent.length();
}
System.out.println("Char : " + currentChar + " Occurance " + (length - sent.length()));
length = sent.length();
}
System.out.println("Max Occurance : " + maxLength);
输出:
Char : a Occurance 3
Char : s Occurance 1
Char : d Occurance 3
Char : A Occurance 1
Char : F Occurance 1
Char : f Occurance 2
Char : e Occurance 2
Frequent Char : a
Max Occurance : 3
关于Java程序找到字符串中出现次数最多的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22034250/