无法找出我的输出打印2次以及StringBuilder

时间:2017-10-07 19:03:35

标签: java stringbuilder

我正在使用一个StringBuilder,并为要猜到的单词的每个字母附加*。然后当用户猜出字母/字符正确时,StringBuilder应该将某个索引处的字符从*更改为猜测的字母/字符。然后打印新的StringBuilder以显示正确的字母(ho * s *)。如果猜测错误,那么只需打印StringBuilder并说出错误的猜测。

我想弄清楚为什么这不能正常工作。我得到的结果如下:(减去/它不会只发布*)

吊颈

尝试并猜测这个词,你有9次尝试:

/ ***************

猜一封信:g

/ ********

猜一封信: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());
    }

 }

1 个答案:

答案 0 :(得分:1)

你用这一行覆盖任何正确的猜测:

using

在您的sb.setCharAt(i, '*'); 方法中,因此您应将其删除。

此外,您的打印语句位于findMatch循环中,因此每个单词都会打印出 n 次。通过将您的呼叫转移到for循环之外的System.out.print(sb.toString())来解决此问题。

这会让你:

for