[英]Converting an array of 26 integers to char's (alphabet)
我正在使用Java掃描儀從鍵盤輸入文本字符串,然后讓我的程序創建一個輸出az的表,並顯示在輸入字符串中找到的每個字母的編號。 (字母頻率)
我的司機/主班
import java.util.*;
public class LetterDriver{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
LetterProfile profile = new LetterProfile();
String tScan = " ";
int numReturns = 0;
while(numReturns < 2){
tScan = s.nextLine();
if (tScan.length() == 0){
numReturns++;
}
else{
profile.countChars(tScan);
numReturns = 0;
}
}
profile.printResults();
}
}
我的個人資料課
public class LetterProfile {
int score[] = new int [26];
public void countChars (String s) {
s = s.toLowerCase();
char a = 'a';
for (int i = 0; i < s.length(); i++) {
int next = (int)s.charAt(i) - (int) a;
if ( next<=26 && next >= 0)
score[next]++;
}
}
public int largestLength() {
int largest = 0;
int largestindex = 0;
for(int a = 0; a<26; a++) {
if(score[a] > largest) {
largest = score[a];
largestindex = a;
}
}
return (char)largestindex;
}
public void printResults() {
largestLength();
System.out.println(("Most Frequent") + (" :") + largestLength());
}
}
該程序進行編譯,當我運行它時,它允許我輸入內容,但它給我的唯一輸出是以數字形式出現的最常用的字母(因為我的數組是0-25,其中0 = a,1 = b)
基本上,我遇到的麻煩是讓我的代碼輸出az表,同時在其旁邊顯示字母頻率。 有沒有簡單的方法可以做到這一點?
謝謝。
我不確定我是否理解-當然,它所做的只是打印最頻繁的字母-這就是printResults
方法所做的全部。
只需遍歷score
數組並在對應字母旁邊打印每個樂譜,您便應該擁有整個頻率表。
將此添加到printResults
方法中已有的代碼中。 結果是它將首先打印最頻繁的字母,然后打印以數字1開頭的字母頻率列表。
for (int i = 0; i < score.length; i++) {
System.out.println( (i+1) + ": " + score[i]);
}
例如:
Most frequent: e
1: 5
2: 0
3: 2
4: 0
5: 15
...
等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.