简体   繁体   中英

Printing the frequency of of characters in a user inputted string using ASCII (Java)

I've already converted the strings characters to ASCII and converted them values to binary but I'm wondering how to print the values of each character Eg if the user inputted "Hello" it would run as h,e,l,l,o in binary and print "frequency of l = 2" kind of thing .. I've written what I think could be used but anything after where I initialsie the array of size 256 is probably incorrect Any help would be much appreciated as to what I'm doing wrong

import java.util.Scanner;
public class test2{
    public static void main(String[] args){
       System.out.print("Enter your sentence : ");
       Scanner sc = new Scanner(System.in);
       String name = sc.nextLine();
       int counter = 0;
       for(int i =0; i < name.length(); i++){
           char character = name.charAt(i);
           int ascii = (int) character; 
           Integer.toBinaryString(ascii);
           System.out.println(Integer.toBinaryString(ascii));

           int[]array = new int[256];

           for(int j = 0; j<array.length; j++){
               array[ascii]++;// if you have an ascii character, increment a slot of your afray
               while(ascii>0){ //while an element is bigger than 0, print
                   System.out.println(array);
                }
            }

       }
    }
}

You can just print the frequency of characters only if it is not 0.

import java.util.Scanner;

public class test2
{
    public static void main( String[] args )
    {
        System.out.print( "Enter your sentence : " );
        Scanner sc = new Scanner( System.in );
        String name = sc.nextLine();
        sc.close();

        int[] array = new int[256];

        for ( int i = 0; i < name.length(); i++ )
        {
            char character = name.charAt( i );
            int ascii = ( int )character;
            System.out.println( character + " = " + Integer.toBinaryString( ascii ) );
            array[ascii]++;
        }

        for ( int i = 0; i < array.length; i++ )
        {
            if ( array[i] > 0 )
            {
                System.out.println( "Frequency of " + (char)i + " = " + array[i] );
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM