[英]Can not find out why my output is printing 2 times and how swap chars in StringBuilder
我正在使用 StringBuilder 並為要猜測的單詞的每個字母附加 * 。 然后,當用戶猜測正確的字母/字符時,StringBuilder 應該將某個索引處的字符從 * 更改為猜測的字母/字符。 然后打印新的 StringBuilder 以顯示正確的字母(ho * s *)。 如果猜測是錯誤的,那么只需打印 StringBuilder 並說出錯誤的猜測。
我想弄清楚為什么這不能正常工作。 我得到的輸出如下:(減去 / 它不會只發布 *)
劊子手
試着猜這個詞,你有 9 次嘗試:
/****************
猜一個字母:g
/*****************************
猜一個字母:p
p****p****p****p****p****
猜一封信
它也不止一次打印這個詞,我不知道為什么。
import java.util.Random;
import java.util.Scanner;
public class Hangman {
static String[] words = {"house", "show", "garage", "computer", "programming", "porch", "dog"};
static char[] correct = new char[26];
static char[] wrong = new char[26];
static char guess;
static Random generator = new Random();
static Scanner input = new Scanner(System.in);
static String word;
static int attempts = 0;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args){
word = words[generator.nextInt(words.length)];
System.out.print("HANGMAN\nTry and guess the word, you have 9 attempts: \n");
printAstrick();
while(attempts <= 9){
System.out.print("\nGuess a letter: ");
guess = input.next().charAt(0);
findMatch(guess);
}
if(attempts == 9){
System.out.println("Your attempts are up");
}
}
public static void findMatch(char c){
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == c){
correct[i] = c;
sb.setCharAt(i, c);
System.out.print(sb.toString());
}
else if(word.charAt(i) != c){
wrong[i] = c;
sb.setCharAt(i, '*');
System.out.print(sb.toString());
}
}
attempts++;
}
public static void printAstrick(){
for(int i = 0; i < word.length(); i++){
sb.append("*");
System.out.print(sb.toString());
}
}
您正在使用此行覆蓋任何正確的猜測:
sb.setCharAt(i, '*');
在您的findMatch
方法中,因此您應該將其刪除。
此外,您的打印語句在for
循環中,因此每個單詞都會打印n次。 通過將您的調用移到for
循環之外的System.out.print(sb.toString())
來解決此問題。
這給你留下:
public static void findMatch(char c) {
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == c) {
correct[i] = c;
sb.setCharAt(i, c);
} else if (word.charAt(i) != c) {
wrong[i] = c;
}
}
System.out.print(sb.toString());
attempts++;
}
public static void printAstrick() {
for (int i = 0; i < word.length(); i++) {
sb.append("*");
}
System.out.print(sb.toString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.