简体   繁体   English

使用ASCII(Java)打印用户输入的字符串中字符的频率

[英]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 我已经将字符串字符转换为ASCII并将它们的值转换为二进制,但是我想知道如何打印每个字符的值,例如,如果用户输入“ Hello”,它将以h,e,l,l,o运行以二进制形式并打印“ l = 2的频率”之类的东西..我已经写了我认为可以使用的东西,但是在我初始化为256大小的数组之后的任何东西都可能是不正确的。做错了

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. 仅当字符频率不为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] );
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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