我已经将字符串字符转换为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 :(得分:2)
只有字符不是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] );
}
}
}
}