首页 文章

Java中的基本hangman程序

提问于
浏览
-2

我需要了解条件是否字母是x y z并且我无法得到它的逻辑 .

package guessword;

import java.util.*;

public class Guessword {       
    public static void main(String[] args) {   
        char s[] = {'a','b','c','d','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        System.out.println("Guess The seven letter word\nPress Enter");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        System.out.print("");
        for(int a=1;a<=7;a++){
            System.out.println("Attempt "+a);
            scanner = new Scanner(System.in);
            String input = scanner.nextLine();
            System.out.println(Arrays.toString(s));       
            if(a=='a') {
                System.out.println("- - - - - a -"); 
            }
            else if(a=='g'){
                System.out.println("- - - g - - -");
            }
            else if(a=='m') {
                System.out.println("- - -  - - m");
            }
            else if(a=='o') {
                System.out.println("- - o  - - -");
            }
            else if(a=='p'){
                System.out.println("p - -  - - -");
            }
            else if(a=='r'){
                System.out.println("- r -  - - -");
            }
            else {
                System.out.println("Give it another go!");
            }
        }
    }  
}

这就是输出的方式:

Guess The seven letter word
Press Enter

Attempt 1
a
[a, b, c, d, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
Give it another go!
Attempt 2

在这个 [a, b, c, d, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] 行,我希望它不打印这个 . 但条件 .

1 回答

  • 0

    您正在检查错误的输入,因为 a 是一个数字,用户输入是 input . 你也在比较 String 所以你必须像这样使用 equals

    if(input.equals("a")) {
        System.out.println("- - - - - a -"); 
    } else if(input.equals("g")) {
        System.out.println("- - - g - - -");
    } else if(input.equals("m")) {
        System.out.println("- - -  - - m");
    } // and so on...
    

    你可能想在主循环之前初始化 Scanner 并在它之后关闭它,如下所示:

    scanner = new Scanner(System.in);
    for(int a=1;a<=7;a++){
        System.out.println("Attempt "+a);
        // some code ...
    }
    scanner.close();
    

    最后但并非最不重要的是,每次调用 System.out.println(Arrays.toString(s)); 时都会打印数组,因此如果不希望它出现在控制台上,则必须将其删除 .

相关问题