簡體   English   中英

使用ASCII(Java)打印用戶輸入的字符串中字符的頻率

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

我已經將字符串字符轉換為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);
                }
            }

       }
    }
}

僅當字符頻率不為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