Java 打破一种方法的困难

Java 打破一种方法的困难,java,for-loop,methods,boolean,Java,For Loop,Methods,Boolean,我的方法很难回到真实的状态。这是一种布尔方法,它使用两个单词,并尝试通过转置两个相邻的字母来查看是否可以将一个单词转换为另一个单词。我在获取假布尔值时没有遇到任何问题。当代码到达包含if语句的for循环时,它运行良好,但在满足if语句时不会返回true。出于某种原因,它会继续通过For循环。例如,当比较teh和when循环命中1时,if语句满足但不返回true,For lo public static boolean transposable(String word1, String word2

我的方法很难回到真实的状态。这是一种布尔方法,它使用两个单词,并尝试通过转置两个相邻的字母来查看是否可以将一个单词转换为另一个单词。我在获取假布尔值时没有遇到任何问题。当代码到达包含if语句的for循环时,它运行良好,但在满足if语句时不会返回true。出于某种原因,它会继续通过For循环。例如,当比较teh和when循环命中1时,if语句满足但不返回true,For lo

public static boolean transposable(String word1, String word2)
    {
        ArrayList<Character> word1char = new ArrayList<Character>();
        ArrayList<Character> word2char = new ArrayList<Character>();
        int word1length = word1.length();
        int word2length = word2.length();
        int count = 0;
        String w1 = word1.toUpperCase();
        String w2 = word2.toUpperCase();
        if(word1length != word2length)
        {
            return false;
        }
        for(int i = 0; i < word1length; i++)
        {
            char letter1 = w1.charAt(i);
            word1char.add(letter1);
            char letter2 = w2.charAt(i);
            word2char.add(letter2);
        }
        for(int i = 0; i < word1length; i++)
        {
            char w1c = word1char.get(i);
            char w2c = word2char.get(i);
            if(w1c == w2c)
            {
                count++;
            }
        }
        if(count < word1length - 2)
        {
            return false;
        }
        for(int i = 0; i < word1length; i++)
        {
            char w1c = word1char.get(i);
            char w2c = word2char.get(i+1);
            if(w1c == w2c)
            {
                return true;
            }
        }
        return false;
    }

op一直在运行。我做错了什么?

正如评论中指出的,这似乎不是解决这个问题的最简单方法。下面是一个尝试遵循您的逻辑的解决方案,包括使用toUpperCase和ArrayList

检查代码时,看起来您的逻辑有点迷失了。这是因为你有一种方法尝试做每件事。将事情分解成更小的方法,您也将受益于不必重复代码,这样可以使事情更干净。下面的代码是用Java8测试的,尽管没有理由不使用Java7

public static void main(String args[]) {
    String word1 = "Hello";
    String word2 = "Hlelo";

    transposable(word1, word2);

}

private static boolean transposable(String word1, String word2) {
    // Get an ArrayList of characters for both words.
    ArrayList<Character> word1CharacterList = listOfCharacters(word1);
    ArrayList<Character> word2CharacterList = listOfCharacters(word2);

    boolean areWordsEqual;

    // Check that the size of the CharacterLists is the same
    if (word1CharacterList.size() != word2CharacterList.size()) {
        return false;
    }

    // check to see if words are equal to start with
    areWordsEqual = checkIfTwoWordsAreTheSame(word1CharacterList, word2CharacterList);
    System.out.print("\n" + "Words are equal to be begin with = " + areWordsEqual);

    if (!areWordsEqual) {

      /*
      This loop i must start at 1 because you can't shift an ArrayList index of 0 to the left!
      Loops through all the possible combinations and checks if there is a match.
      */
        for (int i = 1; i < word1CharacterList.size(); i++) {
            ArrayList<Character> adjustedArrayList = shiftNeighbouringCharacter(word2CharacterList, i);
            areWordsEqual = checkIfTwoWordsAreTheSame(word1CharacterList, adjustedArrayList);
            System.out.print("\n" + "Loop count " + i + " words are equal " + areWordsEqual + word1CharacterList + adjustedArrayList.toString());
            if (areWordsEqual) {
                break;
            }
        }
    }

    return areWordsEqual;
}

// takes in a String as a parameter and returns an ArrayList of Characters in the order of the String parameter. 
private static ArrayList<Character> listOfCharacters(String word) {
    ArrayList<Character> wordCharacters = new ArrayList<Character>();
    String tempWord = word.toUpperCase();

    for (int wordLength = 0; wordLength < tempWord.length(); wordLength++) {
        Character currentCharacter = tempWord.charAt(wordLength);
        wordCharacters.add(currentCharacter);
    }
    return wordCharacters;
}

// takes in two character arrayLists, and compares each index character.
private static boolean checkIfTwoWordsAreTheSame(ArrayList<Character> characterList1, ArrayList<Character> characterList2) {
    // compare list1 against list two
    for (int i = 0; i < characterList1.size(); i++) {
        Character currentCharacterList1 = characterList1.get(i);
        Character currentCharacterList2 = characterList2.get(i);

        if (!currentCharacterList1.equals(currentCharacterList2)) {
            return false;
        }
    }
    return true;
}

// this method takes in an ArrayList of characters and the initial index that we want to shift one place to the left. 
private static ArrayList<Character> shiftNeighbouringCharacter(ArrayList<Character> characterListToShift, int indexToShiftLeft) {
    ArrayList<Character> tempCharacterList = new ArrayList<Character>();
    int indexAtLeft = indexToShiftLeft - 1;

    // fill the new arrayList full of nulls. We will have to remove these nulls later before we can add proper values in their place.
    for (int i = 0; i < characterListToShift.size(); i++) {
        tempCharacterList.add(null);
    }

    //get the current index of indexToShift
    Character characterOfIndexToShift = characterListToShift.get(indexToShiftLeft);
    Character currentCharacterInThePositionToShiftTo = characterListToShift.get(indexAtLeft);

    tempCharacterList.remove(indexAtLeft);
    tempCharacterList.add(indexAtLeft, characterOfIndexToShift);

    tempCharacterList.remove(indexToShiftLeft);
    tempCharacterList.add(indexToShiftLeft, currentCharacterInThePositionToShiftTo);


    for (int i = 0; i < characterListToShift.size(); i++) {

        if (tempCharacterList.get(i) == null) {
            Character character = characterListToShift.get(i);
            tempCharacterList.remove(i);
            tempCharacterList.add(i, character);
        }
    }
    return tempCharacterList;
}

希望这有帮助。如果您仍在挣扎,请在调试器中继续操作:

您是如何确定for循环一直在运行的?另外,在访问word2char.geti+1时,您的最终循环将在最后一个字符处抛出ArrayIndexOutOfBoundsException。这似乎是一种过于复杂的方法。如果是我的话,我只需要取一个单词,将两个字母的所有组合转换成一组,然后检查第二个单词是否在该组中。@Falmari你的方式对我来说更复杂。。。唯一真正使OP代码复杂化的事情是像手动/不必要地将字符串打包到ArrayList之类的想法,但所有这些都可能是被问到的问题的附带问题。我想说for循环继续运行是错误的说法。我让系统在if语句之后打印I值,以查看它何时到达某个点,并让系统打印if语句中的两个单词。它循环了一次,打印了0,返回并打印了两个单词,然后又打印了0,然后打印了1,然后崩溃了。谢谢你的回答!我昨天忘了发布这篇文章,但我最终保持了代码完全相同,只是我更改了for循环,使其在数组大小不足1的情况下停止,这样它就不会抛出异常。这似乎解决了我的问题,但我仍然不确定为什么它没有在返回语句开始时中断。此外,我在一个初级班,所以我只是在使用我们已经介绍过的东西。这是我能想到的最简单的方法。很高兴你能让代码正常工作。未来可能对你有所帮助的一条经验法则是问问你自己——这种方法有什么用?你会发现自己在说什么,然后建议你可能需要将零件移动到和之后的另一种方法中。例如,此方法从字符串中提取字符,将其放入ArrayList,并检查它们是否相同。应为两条语句。此方法从字符串中提取字符,将其放入ArrayList,此方法检查两个ArrayList中的字符是否相同。哦,差点忘了,另一个在开始时要尽快学习的好东西是如何使用IDE调试器。Eclipse和Intellij具有出色的调试功能,只需学习基本知识,就可以在执行代码时逐步完成。最后,这可能是因为您的班长希望您按照您的方式格式化代码,但Java编码惯例规定,大括号{}应该出现在声明语句的同一行末尾,并单独开始一行,就像我的回答中那样。