2013-03-19 76 views
1

我正在使用java掃描儀從鍵盤輸入文本字符串,然後讓程序創建一個表,輸出az並顯示輸入字符串中找到的每個字母的編號。 (字母頻率)將26個整數的數組轉換爲字符(字母)

我的司機/主類

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)

基本上我在嘗試做的麻煩是讓我的代碼輸出在在顯示旁邊的字母頻率的同時可以顯示a-z。有沒有簡單的方法來完成這件事?

謝謝。

回答

2

我不確定我是否理解 - 當然,它所做的只是打印最頻繁的信件 - 這就是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 
... 

等等

+0

我很難找出如何去做這件事的方法 – aiuna 2013-03-20 00:09:00

+0

啊哎呀。用循環更新 - 我的不好。 – jefflunt 2013-03-20 00:10:05

+0

哇,最後有點進展我現在遇到的唯一問題是在旁邊顯示字母而不是數字。非常感謝。 – aiuna 2013-03-20 00:16:55

0

試試這個:

for (int i = 0; i<score.length; i++){ 
System.out.println(score[i]); 
} 

並且還給this一個閱讀以熟悉sta tements。

相關問題