这是我目前所拥有的.假设我会猜香蕉".将显示用户输入的字母,其余字母标记为*".==============================================问题:它将包括"在内的整个值附加到 arrayList 中存储值的末尾,而不是我想要的特定位置.("也应该附加时不包括在内.仅包括用户输入的字母).*刽子手游戏的逻辑.示例:输入的第一个字母:a"输出:_a_a_a输入的第二个字母:n"输出:_ _n_n_(这是错误的)正确的输出应该是:_anana==============================================我是字符串操作的新手,我在这部分遇到了问题.我已经阅读了一些关于 StringBuilder 的内容,但我还没有弄清楚.如果你能帮助我,那就太好了.提前致谢.:) 解决方案 没错,这可以使用 StringBuilder 来完成.您只需要将包含 char 的原始 String 中索引处的 char 替换为 char,这可以使用 setCharAt.以下代码也保持空格字符不变,这也是构造函数中对空格进行特殊处理的原因.import java.text.MessageFormat;公共类 StringReveal {私人最终字符串原件;私人最终 StringBuilder stringBuilder;私人字符串 currentString;private int missingLetters;公共 StringReveal(字符串原件,字符占位符){if (original.indexOf(placeholder) >= 0) {throw new IllegalArgumentException("占位符不能包含在字符串中");}如果(Character.isWhitespace(占位符)){throw new IllegalArgumentException("占位符不能是空白字符");}this.original = 原始的;this.stringBuilder = new StringBuilder();this.missingLetters = original.length();for (char c : original.toCharArray()) {如果(Character.isWhitespace(c)){//保持空白字符相同缺少字母--;stringBuilder.append(c);} 别的 {//用占位符字符替换其他所有内容stringBuilder.append(placeholder);}}this.currentString = stringBuilder.toString();}公共无效揭示(char c){int index = original.indexOf(c);if (index = 0);currentString = stringBuilder.toString();}公共字符串 getCurrentString() {返回当前字符串;}公共 int getMissingLetters() {返回丢失的信件;}公共静态无效主(字符串 [] args){StringReveal stringReveal = new StringReveal("香蕉面包", '*');char[] 猜测 = {'a', 'x', 't', 'a', 'b', 'k', 'n', 'g', 'd', ' ', '*', 'r', 'w', 'e'};System.out.println("试着猜一猜:" + stringReveal.getCurrentString());对于(字符猜测:猜测){stringReveal.reveal(猜测);System.out.println(MessageFormat.format("Current String: {0} ; guess: ''{1}''; 你还要猜 {2} 个字母",stringReveal.getCurrentString(),猜测,stringReveal.getMissingLetters()));}}}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 userrevealed - is a declared as a BitSetint sizeReset - is the size of the word to guessASSUME 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_asecond 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())); } }} 这篇关于将 arraylist 中的字符追加到特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-25 01:09