Java 猜词游戏

Java 猜词游戏

1.1题目说明

	随机产生一个单词,提示用户每次猜一个字母。单词中的每个字母以星号显示。当用户 猜对一个字母时,显示实际字母。当用户完成一个单词时,显示猜错的次数,同时询问用户是否继续下一单词。单词存储使用数组形式,如:String[] words = {“write”,”that”,…};

1.2 分析过程

​ 用户开始,使用chooseWord()在定义的字符串数组中随机产生一个单词,使用名为label的char类型的数组,里面的每个字母设置为*,然后用户进行猜测,一共有七次猜测的机会,每进行一次猜测,如果猜测成功,则输出该字母在单词中的位置,否则输出该字母没有在单词中,如果在猜测七次中,猜对该单词,则退出for循环,输出单词和用户猜错的次数,如果七次结束之后没有猜测出该单词,则输出猜错七次,然后询问用户是否进行下一局,如果用户输入y,则返回重新开始游戏,如果用户输入n,则结束游戏。

相关函数:chooseWord():在定义的字符串数组中随机产生一个字符串

1.3 系统测试

在这里插入图片描述

1.4代码展示

package version1;

import java.util.Random;
import java.util.Scanner;

/**
 * @Auther: paradise
 * @Date: 2021/6/24 - 06 - 24 - 16:19
 */
public class Guess {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] words = {"write", "that", "pearson", "animal", "program", "intro"};

        while (true) {
            String word = chooseWord(words);
            int count = 0;

            //label是星号的表示方法
            char[] label = new char[word.length()];
            for (int i = 0; i < word.length(); i++) {
                label[i] = '*';
            }

            //用户允许输入7次
            for (int i = 0; i < 7; i++) {
                System.out.print("Enter a letter in the word ");
                for (int j = 0; j < label.length; j++) {
                    System.out.print(label[j]);
                }
                System.out.print(":");

                String letter = input.next();
                char firstChar = letter.charAt(0);

                if (word.indexOf(firstChar) != -1) {
                    for (int j = 0; j < word.length(); j++) {
                        if(firstChar == word.charAt(j))
                            label[j] = firstChar;
                    }
                } else {
                    System.out.println(firstChar + " is not in the word");
                    count++;
                }
                //如果猜的已经和原单词一样了,那么退出此循环
                String newString = new String(label);
                if(newString.equals(word))
                    break;
            }
            System.out.println("The word is " + word + ".You missed " + count + " times.");

            System.out.println("Do you want to guess for another word? Enter y or n");
            String s = input.next();

            if (s.equals("y")) {
                continue;
            }
            else if (s.equals("n")) {
                break;
            }else {//非法输入退出
                System.out.println("无效输入");
                System.exit(0);
            }
        }
    }

    //选择数组中一个元素的方法
    public static String chooseWord(String[] s){
        Random random = new Random();
        int n = random.nextInt(s.length);
        String word = s[n];
        return word;
    }
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>