有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

排序后的java输出?

我正在制作一个程序,从用户那里获取一个短语,然后对元音进行计数,然后根据计数按升序显示所有元音

其外观的示例:

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

请帮我正确打印这个


共 (1) 个答案

  1. # 1 楼答案

    请参见代码中的我的注释以进行排序:

        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;
        }