?? wordcounter.java
字號:
/**
* 實驗7-題目2:單詞統計問題,使用2種方法實現
*/
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class WordCounter {
// 求一個字符串數組中最長字符串的長度
public static int maxStringLen(String[] strs) {
int maxLen = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i].length() > maxLen) {
maxLen = strs[i].length();
}
}
return maxLen;
}
//顯示結果
public static void displayResult(int[] result) {
int count = 0;
System.out.printf("%4s %4s\n", "單詞長度", "單詞個數");
System.out.println("------------------");
for (int i = 0; i < result.length; i++) {
System.out.printf("%4d %4d\n", i + 1, result[i]);
count += result[i];
}
System.out.println("------------------");
System.out.println("合計:" + count);
}
//使用Tonkenizer類實現
public static void countWithTokenizer(String str) {
StringTokenizer st = new StringTokenizer(str);
int totalWords = st.countTokens();
String[] strs = new String[totalWords];
int i = 0;
while (st.hasMoreTokens()) {
strs[i++] = st.nextToken();
}
int[] result = new int[maxStringLen(strs)];
for (i = 0; i < strs.length; i++) {
result[strs[i].length() - 1]++;
}
//輸出結果
displayResult(result);
}
//使用String類的split方法實現
public static void countWithSplit(String str) {
String[] strs = str.split(" ");
int[] result = new int[maxStringLen(strs)];
for (int i = 0; i < strs.length; i++) {
result[strs[i].length() - 1]++;
}
//輸出結果
displayResult(result);
}
public static void main(String[] args) {
String str = JOptionPane.showInputDialog(null, "Input a String",
"Word Conuter", JOptionPane.QUESTION_MESSAGE);
System.out.println("使用StringTokenizer處理:");
countWithTokenizer(str);
System.out.println("使用String的split方法處理:");
countWithSplit(str);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -