将arraylist中的字符附加到特定位置

2022-01-22 00:00:00 append java

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. :)

解决方案

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()));
        }
    }

}

相关文章