第一次就記錄給java的第五次作業吧
阿新 • • 發佈:2019-02-14
package examples; import java.util.*; /** * Created by Kazami Hatsuroku on 2017/6/5. */ public class CalWords { Scanner sc; String[] str = new String[100]; String[] noRedundant = new String[100]; int[] occurrence = new int[100]; int count=0, sameWordSum=0, notSameWordSum=0; CalWords(Scanner sc){ this.sc = sc; sc.useDelimiter("[^a-zA-Z']+"); while (sc.hasNext()) { str[count] = sc.next(); count++; //count是單詞總數 } calSameWords(); calOccurrence(); } void calSameWords(){ boolean flag=true; for (int i = 0; i < count; i++) { for(int j = 0; j < notSameWordSum; j++) { if (str[i].equalsIgnoreCase(noRedundant[j])){ flag=false; sameWordSum++; } } if(flag){ noRedundant[i-sameWordSum]=str[i]; notSameWordSum++; //notSameWordSum就是不重複的單詞的總數} flag=true; } } void calOccurrence(){ for (int i = 0; i < notSameWordSum; i++) { for (int j = 0; j < count; j++) { if(noRedundant[i].equalsIgnoreCase(str[j])){ occurrence[i]++; } } } } void printByOrder(){ boolean flag = true; int max = 0; for (int i = 0; i < notSameWordSum; i++) { if(occurrence[i] > max){ max=occurrence[i]; } } while(max > 0){ for (int i = 0; i < notSameWordSum; i++) { if (flag){ System.out.printf("這是出現過%d次的單詞:",max); flag = false; } if (occurrence[i]==max){ System.out.print(noRedundant[i]+" "); } } System.out.println(); max--; flag = true; } } }