刽子手游戏错误

时间:2016-12-09 18:29:37

标签: java

我写的这个代码是一个刽子手游戏 但是,当用户输入所有字母时,代码会继续运行,除非我写下这个字以便恭喜用户。

我想让它在用户输入所有正确的字母时停止

import java.util.Scanner;
public class question6 {

    public static void main(String[] args) {

        String str = "testing";
        boolean[] strBoolean = new boolean[str.length()];
        Scanner input = new Scanner(System.in);
        String test = "";
        int counter = 1;
        System.out.println("Java word guessing testing");

            // main for loop for guessing the letters
            while(true){
                System.out.println("Key in one word character or your guessed word:");
                test = input.nextLine();

                if(test.equals(str)){
                    System.out.println("Congratulation!");
                    break;
                }else{

                    // for loop for checking the boolean array
                    for(int b=0; b<strBoolean.length; b++){
                        if(str.charAt(b) == test.charAt(0)){
                            strBoolean[b] = true;
                        }                   
                    }

                    // for loop for printing the correct letters
                    System.out.print("Trail "+counter+": ");
                    for(int j=0; j<str.length(); j++){
                        if(strBoolean[j] == true){
                            System.out.print(str.charAt(j));
                        }else{
                            System.out.print("_");
                        }
                    }
                    System.out.println();
                    counter++;
                }
            }
    }

    }

1 个答案:

答案 0 :(得分:0)

首先,您正在尝试将字符串test与字符串str进行比较,但由于您在进行该比较之前接受test的新用户输入,因此只有当用户键入&#34; testing&#34;时才会成真。因此,请确保在将来的案例中跟踪程序说明中的顺序。

您通过使用布尔值数组来跟踪用户的进度。因此,您可以创建一个方法来检查所述数组中的所有值是否为true,如果是,则返回true。见例:

import java.util.Scanner;
public class question6 {

    public static void main(String[] args) {

        String str = "testing";
        boolean[] strBoolean = new boolean[str.length()];
        Scanner input = new Scanner(System.in);
        String test = "";
        int counter = 1;
        System.out.println("Java word guessing testing");

            // main for loop for guessing the letters
            while(true){
                if(allTrue(strBoolean)){
                    System.out.println("Congratulation!");
                    break;
                }else{
                    System.out.println("Key in one word character or your guessed word:");
                    test = input.nextLine();
                    // for loop for checking the boolean array
                    //and the rest of your code
                }
            }

    }
    public static boolean allTrue (boolean[] values) {
        for (int index = 0; index < values.length; index++) {
            if (!values[index]){
                return false;
            }
        }
        return true;
    }
}