JAVA三星题之hangman

题目:Write a hangman game that randomly generates a word and prompts the user to guess one letter at a time,as shown in the sample run.Each letter in the word is displayed as an asterisk.When the user finishes a word,display the number of misses and ask the user whether to continue for another word.Declare an array to store words,as follows:
String[] word = {"write","that",...};

题目来源:

题目选自《JAVA程序语言设计》 P341-9.31***

代码如下:

import java.util.Scanner;

public class HangmanDemo {
	Scanner input = new Scanner(System.in);
	private String[] words = { "write", "that", "program", "problem",
			"yourself" };

	public HangmanDemo() {
		while (true) {
			int num = (int) (Math.random() * 5);
			String str = words[num];
			int n = Guess(str);
			System.out.println("The word is " + str + ". You missed " + n
					+ " time.\n");
			System.out
					.print("Do you want to guess for another word? Enter y or n>");
			String s = input.next();
			if (s.equals("n"))
				break;
		}
		System.out.println("Game over!");

	}

	int Guess(String str) {
		int count = 0, number = str.length();
		char[] a = new char[number];
		for (int i = 0; i < number; i++) {
			a[i] = '*';
		}
		while (true) {
			System.out.print("(Guess) Enter a letter in word ");
			for (int i = 0; i < str.length(); i++) {
				System.out.print(a[i]);
			}
			System.out.print(" > ");
			String letter = input.next();
			int m = 0;
			for (int i = 0; i < str.length(); i++) {
				if (a[i] == letter.charAt(0)) {
					System.out.println("    " + letter
							+ " is already in the word");
					m=1;
				} else if (str.charAt(i) == letter.charAt(0)) {
					a[i] = letter.charAt(0);
					number--;
					m = 1;
				}
			}
			if (m == 0) {
				System.out.println("\t" + letter + " is no in the word");
				count++;
			}
			if (number == 0)
				break;
		}
		return count;
	}

	public static void main(String[] args) {
		new HangmanDemo();
	}

}

运行结果:

(Guess) Enter a letter in word ******* > p
(Guess) Enter a letter in word p****** > s
	s is no in the word
(Guess) Enter a letter in word p****** > r
(Guess) Enter a letter in word pr***** > p
    p is already in the word
(Guess) Enter a letter in word pr***** > m
(Guess) Enter a letter in word pr****m > o
(Guess) Enter a letter in word pro***m > b
(Guess) Enter a letter in word prob**m > l
(Guess) Enter a letter in word probl*m > e
The word is problem. You missed 1 time.

Do you want to guess for another word? Enter y or n>n




  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值