2016-10-03 55 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