[英]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.