HangmanDemo

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();
		}

	}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值