append characters in arraylist in a specific position

陌路散爱 提交于 2019-12-08 04:34:31

问题


public void reveal(char c) {

    for(int i = 0; i < sizeReset; i++) {
        if(wordCompare.charAt(i) == c)  revealed.set(i);
        if(revealed.cardinality() == 0) {
            eo.add(String.valueOf('*'));
        }
        else {
            if(revealed.get(i) == true) {
                eo.add(String.valueOf(wordCompare.charAt(i)));
            }
            else {
                eo.add(String.valueOf('*'));
            }
        }

}
    System.out.println(eo.toString());
    jTextPane1.setText(eo.toString().replace("[", "").replace("]", "").replace(",", "")); 
}

Note:

String wordCompare - contains the word to guess.

char c - is the letter being entered by the user

revealed - is a declared as a BitSet

int sizeReset - is the size of the word to guess

ASSUME THAT ArrayList eo = new ArrayList(); is declared outside the method. (global)

=============================================

This is what I have so far. Let's say I'll be guessing "banana". the entered letter by the user will be shown, and the rest will be marked as "*".

===========================================

PROBLEM: It appends the entire values including the "" to the end of the stored values in the arrayList and not in the specific position that I want them to be.(also the "" should not be included when it appends. only the letters that the user entered). *THE LOGIC OF THE HANGMAN GAME.

SAMPLE:

first letter entered: "a"

OUTPUT:

_a_a_a

second letter entered: "n"

OUTPUT:

_ _n_n_

(which is wrong)

The correct OUTPUT should be:

_anana

===============================================

I'm new to String manipulation and I'm having trouble with this part. I've read something about StringBuilder but I haven't figured it out yet. It would be really great if you can help me. Thanks in advance. :)


回答1:


You're right, this can be done using StringBuilder. You just need to replace the chars at the indices in the original String that contained the char with the char, which can be done using setCharAt.

The following code also keeps whitespace characters the same, which is the reason for the special treatment of whitespaces in the constructor.

import java.text.MessageFormat;

public class StringReveal {

    private final String original;

    private final StringBuilder stringBuilder;
    private String currentString;
    private int missingLetters;

    public StringReveal(String original, char placeholder) {
        if (original.indexOf(placeholder) >= 0) {
            throw new IllegalArgumentException("placeholder must not be contained in the string");
        }

        if (Character.isWhitespace(placeholder)) {
            throw new IllegalArgumentException("placeholder must not be a whitespace character");
        }

        this.original = original;
        this.stringBuilder = new StringBuilder();
        this.missingLetters = original.length();

        for (char c : original.toCharArray()) {
            if (Character.isWhitespace(c)) {
                // keep whitespace characters the same
                missingLetters--;
                stringBuilder.append(c);
            } else {
                // replace everything else with placeholder char
                stringBuilder.append(placeholder);
            }
        }
        this.currentString = stringBuilder.toString();
    }

    public void reveal(char c) {
        int index = original.indexOf(c);
        if (index < 0 || currentString.charAt(index) == c) {
            // if letter was already replaced or does not exist in the original
            // there's nothing to do
            return;
        }

        do {
            // replace char
            stringBuilder.setCharAt(index, c);
            missingLetters--;

            // find next char
            index = original.indexOf(c, index + 1);
        } while (index >= 0);

        currentString = stringBuilder.toString();
    }

    public String getCurrentString() {
        return currentString;
    }

    public int getMissingLetters() {
        return missingLetters;
    }

    public static void main(String[] args) {
        StringReveal stringReveal = new StringReveal("banana bread", '*');

        char[] guesses = {'a', 'x', 't', 'a', 'b', 'k', 'n', 'g', 'd', ' ',  '*', 'r', 'w', 'e'};

        System.out.println("Try to guess this sting: " + stringReveal.getCurrentString());

        for (char guess : guesses) {
            stringReveal.reveal(guess);
            System.out.println(MessageFormat.format("Current String: {0} ; guess: ''{1}''; you still have to guess {2} letters",
                    stringReveal.getCurrentString(),
                    guess,
                    stringReveal.getMissingLetters()));
        }
    }

}



回答2:


The Problem is that you store the ArrayList containing the replaced characters in the reveal method. This means that the ArrayList gets created new every time a character is entered. To fix this problem, you have to store the ArrayList outside of the reveal method like this:

package xyz;

public class Name{

     public ArrayList<String> eo = new ArrayList<String>();

     public void reveal(char c){
          // Reveal Code here
     }
}


来源:https://stackoverflow.com/questions/38070355/append-characters-in-arraylist-in-a-specific-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!