2016-10-03 65 views
0

我正在製作一個程序,它需要從用戶那裏獲取一個短語,然後對元音進行計數,然後根據他們的計數以升序排列顯示所有元音。排序後輸出?

它應該是怎樣看

例:

Welcome to the vowel counter and sorter! 
Enter a phrase! 

aaaaaeeeeiiioou 

The vowels and their count: 

u 1 

o 2 

i 3 

e 4 

a 5 

我覺得我的代碼是正確的,除了我真的不知道「元音後做什麼,他們的數量是:我都整理後。元音和計數

int[] vCount = new int[5]; 

    System.out.println("Welcome to the vowel counter and sorter!\nEnter a phrase!"); 
    String input = keyboard.nextLine(); 

    String upInput = input.toUpperCase(); 

    //examine all characters 

    for (int i=0; i<upInput.length(); i++) 
    { 
     switch (upInput.charAt(i)) 
     { 
      case 'A': 
       vCount[0]++; 
       break; 
      case 'E': 
       vCount[1]++; 
       break; 
      case 'I': 
       vCount[2]++; 
       break; 
      case 'O': 
       vCount[3]++; 
       break; 
      case 'U': 
       vCount[4]++; 
       break; 
     } 
    } 

    char[] vArray = {'A', 'E', 'I', 'O', 'U'}; 
    //Bubble Sort 
    boolean hasSwapped = true; 

    while (hasSwapped == true) 
    { 
     hasSwapped = false; //Assumes it is sorted 

     for (int i = 0; i<vCount.length-1; i++) 
     { 
     if (vCount[i] > vCount[i+1]) 
     { 
      int temp = vCount[i]; 
      vCount[i] = vCount[i+1]; 
      vCount[i+1] = temp; 
      hasSwapped = true; 
      char temp2 = vArray[i]; 
      vArray[i] = vArray[i+1]; 
      vCount[i+1] = temp2; 
     } 
     } 
    } 
    System.out.println("The vowels and their count:"); 
    for (int i=0; i<vArray.length; i++) 
    { 
     System.out.println(vArray[i]+ " " +vCount[i]); 
    } 
} 

我的輸出是完全錯誤的,搞砸了我想你需要一個for循環輸出數組,但我的輸出是路要走:

Enter a phrase! 


aaaaaeeeeiiioou 

The vowels and their count: 

U 1 


U 79 


U 79 


U 79 

U 79 

請幫我打印正確嗎?

回答

0

見我在代碼註釋爲您的排序:

if (vCount[i] > vCount[i+1]) 
    { 
     int temp = vCount[i]; 
     vCount[i] = vCount[i+1]; 
     vCount[i+1] = temp; 
     hasSwapped = true; 
     char temp2 = vArray[i]; 
     vArray[i] = vArray[i+1]; 
     vCount[i+1] = temp2; // this line is wrong. reference vArray not vCount 
    } 

作爲一個說明,這樣的問題是,爲什麼你不應該重寫整理自己。有這樣的圖書館。使用char到int的映射來實現這一點會更清晰,並且只需輸出基於最高計數的結果。但是,下面應該解決您的直接問題:

if (vCount[i] > vCount[i+1]) 
    { 
     int temp = vCount[i]; 
     vCount[i] = vCount[i+1]; 
     vCount[i+1] = temp; 
     hasSwapped = true; 
     char temp2 = vArray[i]; 
     vArray[i] = vArray[i+1]; 
     vArray[i+1] = temp2; 
    } 
+0

哇太簡單了我很驚訝,我忽略了這一點!謝謝nhouser,我們剛開始學習數組,我的教授試圖讓我們學習的一個練習是使用「冒泡排序」對數組進行排序,這是我的第一個編程類,所以我對地圖和庫沒有任何瞭解! –

+0

@ChrisM沒問題,很樂意幫忙。請註冊並接受! – nhouser9

+0

會upvote並接受:)順便說一句,我用我的教授的例子排序代碼塊,你能告訴我爲什麼它是vCount.length -1的行:for(int i = 0; i