计算每个名称中的元音,并单独显示

时间:2015-01-29 18:04:08

标签: java arrays count names

我如何使用此代码计算每个单词中的元音,而不是添加所有元音并显示这些元音。我写的代码:

import javax.swing.JOptionPane;
import java.util.Arrays;
String[] names = new String[12];
int i;
int j;
j=0;
int vowelCount;
vowelCount=0;
char ch;
names[0] = JOptionPane.showInputDialog("Please enter a name");
names[1] = JOptionPane.showInputDialog("Please enter a name");
names[2] = JOptionPane.showInputDialog("Please enter a name");
names[3] = JOptionPane.showInputDialog("Please enter a name");
names[4] = JOptionPane.showInputDialog("Please enter a name");
names[5] = JOptionPane.showInputDialog("Please enter a name");
names[6] = JOptionPane.showInputDialog("Please enter a name");
names[7] = JOptionPane.showInputDialog("Please enter a name");
names[8] = JOptionPane.showInputDialog("Please enter a name");
names[9] = JOptionPane.showInputDialog("Please enter a name");
names[10] = JOptionPane.showInputDialog("Please enter a name");
names[11] = JOptionPane.showInputDialog("Please enter a name");

Arrays.sort(names);

System.out.println("Name" + "        " + "Characters" + "    " + "Vowels");

for (i=0; i<12; i++)

 {
   for(j=0; j<names[i].length(); j++)
    {
      ch=names[i].charAt(j);

      if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || 
      ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
        vowelCount ++;
    }


System.out.println(names[i] + "       " +names[i].length() + "             " + vowelCount);

 }

我需要代码接受用户输入的名称(它会这样做),按字母顺序排序名称(它的名称),计算每个名称中的字符(它的名称),然后在每个名称中显示元音。

1 个答案:

答案 0 :(得分:0)

保留某种类型的集合,很可能是ArrayList。在计算元音数量时,请将它们添加到列表中。

//declare collection here
for(j=0; j<names[i].length(); j++)
{
  ch=names[i].charAt(j);

  if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || 
     ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
        vowelCount ++;
        //add ch character to collection
    }
System.out.println(names[i] + "       " +names[i].length() + "             " + vowelCount);
//print vowels in collection

Example use of ArrayList


如果您感兴趣,只是为了获取额外信息,您可以使用多个集合,具体取决于您是否需要值/密钥对,是否允许重复条目,以及是否需要特定订单。此外,它们的表现取决于您的使用方式。

Comparison Chart between different Collection

Collection comparison chart