所以我下面有一段代码,它加载到一个文本文件中并对其进行分析,以显示存储在文本文件中的单词或句子中每个字母的百分比。
我希望能够使用 ASCII
代码,而不是使用 char []
字母。
我不确定如何执行此操作,因此我们将不胜感激!
这是我到目前为止的代码:
import java.io.File;
import java.util.Scanner;
public class testing {
@SuppressWarnings("resource")
public static void main(String[] args){
Scanner scan;
try {
scan = new Scanner(new File("G:/test.txt")); //change directory to load in text file
}
catch (Exception e) {
System.out.println("File was not found ");
return;
}
int[] count = new int[26];
int total = 0;
while(scan.hasNextLine()) {
String text2 = scan.nextLine();
System.out.println ("\n--------------------------------------------------------------------------------------------------------");
System.out.println (" Words loaded in from the file: " + text2);
System.out.println ("--------------------------------------------------------------------------------------------------------");
System.out.print("\n");
System.out.print("");
char[] letters = text2.toCharArray();
char[] letters1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
for(int i = 0; i < letters.length; i++) {
for(int j = 0; j < 26; j++) {
if(letters[i] == letters1[j]) {
count[j]++;
total = total + 1;
break;
}
}
}
for (int i = 0; i < 26; i++){
System.out.format("| "+ letters1[i]+" ");
}
System.out.println ("\n----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
for (int i = 0; i < 26; i++){
float percentage = 0;
if (count[i] > 0)
percentage = ((float) count[i]/total)*100;
System.out.format("| "+percentage+ "%% ");
}
}
}
}
最佳答案
Java 中的 char
只是一个无符号 16 位整数,包含与该字符关联的 Unicode 代码点(至少在 BMP 中)。 Unicode 是 ASCII 的超集,因此您的 char[]
已经包含您正在处理的字符的 ASCII 值。
关于java - 使用 Ascii 字符代替 Char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29302991/