在刽子手双字母的bug

时间:2014-08-30 20:56:15

标签: java arraylist

我遇到双字母问题。当用户输入两次字母时,他们只是互相替换。在开始时,我为userArray分配了一个列表,如果userGuess输入在hiddenWord中,我删除其中一个并用userGuess替换它。我使用.equals()来比较userArray和hiddenWord。我尝试过继续使用;跳到下一个迭代而不删除第一个(双重出现的单词)但是当一个单词有2个d时,它们都具有相同的索引。与挖掘机一样,2 g共享相同的索引。所以当我删除

void getUserInput(ArrayList<Character> thisArray) {
    System.out.println("The word you are trying to guess for contains: " + letteramnt + " letters");
    correct=false;
    ArrayList<Character> userArray = thisArray;
    Scanner ugScanner = new Scanner(System.in);
    correct = false;
    ArrayList<Character>Guesses = new ArrayList<Character>();
    while(correct==false) {
        System.out.println("You have guessed the following:"+ Guesses);
        System.out.println("Enter your guess(character):");
        userGuess = ugScanner.next().charAt(0);
        Guesses.add(userGuess);
        for(char element:hiddenWord) {    
            if(userGuess==element) {   
                System.out.println("Good guess");
                elementindex=hiddenWord.indexOf(element);
                if(userGuess==userArray.get(elementindex)) {
                    System.out.println("continuing");
                    continue;//should skip to next iteration
                }
                userArray.remove(elementindex);//
                userArray.add(elementindex,userGuess);
            }
            if (userArray.equals(hiddenWord)||Guesses.equals(hiddenWord)) {
                correct = true;
                System.out.println("The hidden word was: "+hiddenWord);
                break;

1 个答案:

答案 0 :(得分:0)

elementIndex将是该字母的第一个索引,您需要使用索引扫描hiddenWord字符串,

for(int i=0;i<hiddenWord.length;i++) {    
        element = hiddenWord.charAt(i);
        if(userGuess==element) {   
            System.out.println("Good guess");
            userArray.remove(i);
            userArray.add(i,userGuess);
        }