java语言程序设计第十版(Introduce to java 10th) 课后习题 chapter7-33

java语言程序设计第十版(Introduce to java 10th) 课后习题 chapter7-33

自己纯手工,欢迎讨论

package chapter7;

import java.util.Scanner;

public class T35 {
	static int num = 0;// 猜对字母计数器
	static int number = 0;// 猜词次数计数器

	public static void main(String[] args) {
		String[] words = { "write", "hangman", "game", "that", "randomly", "generates", "word" };
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);

		do {
			String choice = words[(int) (Math.random() * 7)];
			// 单词存到数组里
			char[] word = new char[choice.length()];
			for (int i = 0; i < choice.length(); i++)
				word[i] = choice.charAt(i);
			char[] caiWord = new char[choice.length()];
			for (int i = 0; i < choice.length(); i++)
				caiWord[i] = '*';
			while (num != choice.length()) {
				print(caiWord);
				caiWord = caiCi(caiWord, word, in.next().charAt(0));
			}
			printRight(caiWord);
		} while (in.next().charAt(0) == 'y');

	}

	public static void print(char[] k) {
		System.out.print("(Guess) Enter a letter in word  ");
		System.out.print(k);
		System.out.print("  > ");
	}

	public static void printRight(char[] k) {
		System.out.print("The word is ");
		System.out.print(k);
		if ((number - num == 1) || (number - num == 0))
			System.out.printf(" .You missed %d time\n", (number - num));
		else
			System.out.printf(" .You missed %d times\n", (number - num));
		System.out.print("Do you want to guess another word? Enter y or n>");
	}

	public static char[] caiCi(char[] n, char[] k, char c) {
		number++;
		for (int i = 0; i < k.length; i++) {
			if (c == k[i]) {
				n[i] = c;
			}
		}
		int numRight = 0;
		for (int i = 0; i < n.length; i++) {
			if (n[i] != '*')
				numRight++;
		}
		num = numRight;

		return n;

	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值