试图按元音数量排序,该程序根本不排序

发布于 2025-02-08 03:11:39 字数 1079 浏览 0 评论 0原文

我的目的是计算每个索引中每个字符串中的元音数量,将该数字添加到一个数组中,然后使用气泡排序对两个数组进行排序。 (这是针对一堂课的,我们不允许使用数组或任何阵列。方法。)它没有对此进行排序,我不确定为什么。

public static String[] sortByVowels(String[] a) {
    String[] copy = a.clone();

    int[] numVowels = new int[copy.length];

    for(int i = 0; i < copy.length; i++) {
        for(int j = 0; j < copy[i].length(); j++) {
            int count = 0;
            char ch = copy[i].charAt(j);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            count++;
            }
            numVowels[i] = count;
        }
    }
    for (int c = 0; c < copy.length - 1; c++) {
        for(int d = 0; d < copy.length - c - 1; d++) {
            if (numVowels[d] > numVowels[d+1]) {
                int swapInt = numVowels[d];
                numVowels[d] = numVowels[d+1];
                numVowels[d+1] = swapInt;
                
                String swapString = copy[d];
                copy[d] = copy[d+1];
                copy[d+1] = swapString;
            }
        }
    }
    return copy;
}

My intention was to count he number of vowels in each string in each index, add that number to an array, and then sort both the arrays using bubble sort. (this is for a class, and we are not allowed to use arrays.sort or any of the arrays.methods.) It is not sorting whatsoever and I'm unsure as to why.

public static String[] sortByVowels(String[] a) {
    String[] copy = a.clone();

    int[] numVowels = new int[copy.length];

    for(int i = 0; i < copy.length; i++) {
        for(int j = 0; j < copy[i].length(); j++) {
            int count = 0;
            char ch = copy[i].charAt(j);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            count++;
            }
            numVowels[i] = count;
        }
    }
    for (int c = 0; c < copy.length - 1; c++) {
        for(int d = 0; d < copy.length - c - 1; d++) {
            if (numVowels[d] > numVowels[d+1]) {
                int swapInt = numVowels[d];
                numVowels[d] = numVowels[d+1];
                numVowels[d+1] = swapInt;
                
                String swapString = copy[d];
                copy[d] = copy[d+1];
                copy[d+1] = swapString;
            }
        }
    }
    return copy;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掀纱窥君容 2025-02-15 03:11:39

Akarnokd在评论中解决了它。当我的计数器 int count = 0; 在内部炭环内应该在第一个循环中。谢谢你!

Akarnokd in the comments solved it. My counter int count = 0; was inside the inner char loop when it should've been outside in the first for loop. Thank you!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文