首页 > 解决方案 > 嵌套for循环,不拾取数组中的第一个实例

问题描述

我正在尝试对一个单词进行编码,但我不确定为什么我的 for 循环没有选择第一个实例 0。此方法的输入是“This”和 3。此方法的输出是 klv。所以我的循环一定不能正常工作,因为字母 T 被跳过了。我的循环有什么问题?

String encodeWord(String word, int Shift) {

        //word = "This"
        //Shift = 3, is how far the letter is shifted to the right of the original 
        char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
        char[] temp = word.toCharArray();
        char[] FA = new char[temp.length];
        String tempWord = "";
        StringBuilder sb = new StringBuilder(64);




    for (int x = 0; x < word.length(); x++) {

            for (int y = 0; y < alphabet.length; y++) {
                if (word.charAt(0) == alphabet[y]) {
                    FA[0] = alphabet[y + shift];
                    System.out.println(FA[0]);
                }
            }
        }

        for (int i = 0; i < word.length(); i++) {

            for (int j = 0; j < alphabet.length; j++) {
                if (word.charAt(i) == alphabet[j]) {
                    FA[i] = alphabet[j + shift];
                    sb.append(FA[i]);
                    System.out.println(FA[i]);
                }

            }
        }
        System.out.println(sb);

        return sb.toString();
    }

标签: javaloopsfor-loop

解决方案


字母“T”与字母“t”不同,因此由于您的数组中仅找到字母“t”,程序将找不到字母“T”的匹配项。

您的代码的另一个问题是,如果输入包含字母“x”、“y”或“z”,您将得到一个 Index out of bounds 异常,因为在数组中它们后面没有 3 个字母。


推荐阅读