问题描述:

i have done this

public static void main(String[] args) {

int a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i1=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z = 0;

/initialized the variable and counted each matches./

 System.out.println("enter the string");

Scanner sc= new Scanner(System.in);

String s1=sc.nextLine();

/i m taking a string as a i/p from user

 int a = 0;

for(int i=0;i<(s1.length());i++)

{

if (s1.charAt(i)=='a')

{

a++;

}

if (s1.charAt(i)=='b')

{

b++;

} if (s1.charAt(i)=='c')

{

c++;

} if (s1.charAt(i)=='d')

{

d++;

} if (s1.charAt(i)=='e')

{

e++;

} if (s1.charAt(i)=='f')

{

f++;

} if (s1.charAt(i)=='g')

{

g++;

} if (s1.charAt(i)=='h')

{

h++;

}

if (s1.charAt(i)=='i')

{

i1++;

}

if (s1.charAt(i)=='j')

{

j++;

} if (s1.charAt(i)=='k')

{

k++;

} if (s1.charAt(i)=='l')

{

l++;

} if (s1.charAt(i)=='m')

{

m++;

} if (s1.charAt(i)=='m')

{

m++;

} if (s1.charAt(i)=='n')

{

n++;

} if (s1.charAt(i)=='o')

{

o++;

} if (s1.charAt(i)=='p')

{

p++;

} if (s1.charAt(i)=='q')

{

q++;

} if (s1.charAt(i)=='r')

{

r++;

} if (s1.charAt(i)=='s')

{

s++;

} if (s1.charAt(i)=='t')

{

t++;

} if (s1.charAt(i)=='u')

{

u++;

} if (s1.charAt(i)=='v')

{

v++;

} if (s1.charAt(i)=='w')

{

w++;

}

if (s1.charAt(i)=='x')

{

x++;

} if (s1.charAt(i)=='y')

{

y++;

} if (s1.charAt(i)=='z')

{

z++;

}

/...................................adkjagkdgakjdjakdjg/

}

but its not possible to write whole 26 variables again again for printing also...please sugeest me some another option.

网友答案:

As suggested in comments, use a Map.

For instance:

System.out.println("enter the string");
Scanner sc= new Scanner(System.in);
String s1=sc.nextLine();
if (s1 != null && !s1.isEmpty()) {
    // will display character counts alphabetically
    Map<Character, Integer> count = new TreeMap<Character, Integer>();
    char[] chars = s1.toCharArray();
    for (char c: chars) {
        // no count yet for this character
        if (count.get(c) == null) {
            count.put(c,  1);
        }
        // this character appeared at least once: incrementing count
        else {
            count.put(c,  count.get(c) + 1);
        }
    }
    System.out.println(count);
}

Output

enter the string
abcdeff
{a=1, b=1, c=1, d=1, e=1, f=2}
网友答案:

Best way is to use int array of 26 elements. Let us initialize the array of 26 elements:-

int[] array=new int[26];

Now it can be considered that 0th element is a , 1st element is b and so on. Now suppose we have string str. Now iterating string to its end.

for(int i=0;i<str.length();i++)
{
    array[str.charAt(i)-'a']++;    //Storing occurrence of characters in array
}

Now we have occurrence of characters in array and just iterate over array get all value's print.

for(int i=0;i<26;i++)
{
    char ch=(char)('a'+i);
    System.out.println(ch+":"+array[i]);
}

Or if you want to print only occurring characters:-

for(int i=0;i<26;i++)
{
    char ch=(char)('a'+i);
    if(array[i]>0)
    System.out.println(ch+":"+array[i]);
}
网友答案:

You can try using a Map

String str = "occurrences";
Map<String, Integer> map = new HashMap<>();
 for (char i : str.toCharArray()) {
    Integer value = map.get(i + "");
      if (value != null) {
         map.put(i + "", value + 1);
      } else {
         map.put(i + "", 1);
      }
 }

System.out.println(map);

Out put:

{u=1, e=2, s=1, r=2, c=3, n=1, o=1}
网友答案:

As stated in the comments, if you want to associate a unique key with a value (in your case, a character and its number of occurrences) a Map<Character,Integer> is the correct choice.

There are a number of website that teach you about using maps out there. Here's one for starters. I won't spoon feed you the code, since you are clearly trying to learn.

网友答案:
HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>;  

 for(int i=0;i<(s1.length());i++)
 {
  Integer count = charCountMap(s1.charAt(i));
   if(count == null){
     charCountMap.put(1);
   } else {
     charCountMap.put(++count);
   }
 }

To get number of occurences of a:

 int count = charCountMap.get('a');
网友答案:

You can use the ascii values to achieve that.

    String s;

    int[] arr = new int[26];

    for(char x : s.toLowerCase().toCharArray()){
        arr[x-97]++;
    }
    for(int i=0; i<arr.length; i++){

        System.out.println("Count of "+(char)(97+i)+" :"+arr[i]);

    }
网友答案:
    int[] array = new int[256];
    String str = "sdfdagfvdsgfrewfwqafasfdfa";
    for (int i = 0; i < str.length(); i++) {
        array[str.charAt(i)]++;
    }
    for (int i = 'a'; i <= 'z'; i++) {
        if (array[i] > 0) {
            System.out.println((char) i + ":" + array[i]);
        }
    }
网友答案:

Using 2D array this can do as follows

public class Counter {

private String[][] letterArray;

Counter(){
    String letter = "abcdefghijklmnopqrstuvwxyz";
    letterArray = new String[26][2];

    for(int i = 0; i < letterArray.length; i++){
        letterArray[i] = new String[]{letter.charAt(i)+ "", "0"};
    }
}

void setLetterCount(String sentence){
    for(int i = 0; i < sentence.length(); i++){
        String ch = sentence.charAt(i)+"";
        for(int x = 0; x < letterArray.length; x++){
            String letter = letterArray[x][0].toLowerCase();
            int num = Integer.parseInt(letterArray[x][1].toString());
            if (letter.equals(ch)){
                letterArray[x][1] = ++num+"";
                continue;
            }
        }
    }
}

void printLetters(){
    for(String arr[] : letterArray){
        System.out.println(arr[0]+ " : "+ arr[1]);
    }
}

}

public class CounterApp {

public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);
    Counter counter = new Counter();

    System.out.print("Enter the sentence : ");
    String sentence=sc.nextLine();

    counter.setLetterCount(sentence);
    counter.printLetters();
}

}

网友答案:

Without 2D array

public class LetterCounter {

public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);

    System.out.print("Enter the sentence : ");
    String sentence=sc.nextLine().toLowerCase();

    int arr[] = new int[26];

    for(int i = 0; i < sentence.length(); i++){
        char ch = sentence.charAt(i);
        int num = ((int)ch) - 97;
        arr[num] = arr[num] + 1;
    }

    int ch = 97;
    for(int i : arr){
        if(i > 0) {
            System.out.println(((char)ch)+ " : "+ i);
        }
        ch++;
    }

}

}

相关阅读:
Top