ITeye博客

古诗填字游戏 第四讲091121B

atomcow · 2009-11-27 11:32 · JAVA笔记 · Markdown

老师说这个是网易的一道面试题。 填字游戏.java


import java.util.*;

public class 填字游戏 {

	public static void main(String[] args) {
		String[] poems = "白日依山尽,黄河入海流,欲穷千里目,更上一层楼".split(",");
		String rightWords = "";
		String[] answers = new String[4];
		
		int rightOption = (int)(Math.random()* 4);
		
		//挖去四个字
		for (int i = 0; i < 4; i++) {
			rightWords += poems[i].charAt((int)(Math.random()* 5));
		}
	
		answers[rightoption] = rightWords;
		//生成错误答案
		for (int i = 0; i < answers.length; i++) {
			if (i == rightOption) continue;
			int[] pos = {0,1,2,3};
			for (int j = 0; j < 10; j++) {
				int x = (int)(Math.random()* 4);
				int y = (int)(Math.random()* 4);
				int tmp = pos[x];
				pos[x] = pos[y];
				pos[y] = tmp;
			}
			//生成一个备选的错误答案
			//----------------数字数组转化为文字
			String anAnswer = "" + rightWords.charAt(pos[0]) + rightWords.charAt(pos[1]) + rightWords.charAt(pos[2]) + rightWords.charAt(pos[3]);
			if (anAnswer.equals(rightWords)) {
				i--;
				continue;
			}
			//检测备选答案是否重复
			for (int j = 0; j < i; j++) {
				if (anAnswer.equals(answers[j])) {
					i--;
					continue;
				}
			}
			answers[i] = anAnswer;
		}
		
		//打印诗文
		for (int i = 0; i < poems.length; i++) {
			System.out.println(poems[i].replace(rightWords.charAt(i), '?'));
		}
		//打印选项
		for (int i = 0; i < answers.length; i++) {
			System.out.print((char)('A' + i) + ". ");
			System.out.print(answers[i].charAt(0) + ", ");
			System.out.print(answers[i].charAt(1) + ", ");
			System.out.print(answers[i].charAt(2) + ", ");
			System.out.println(answers[i].charAt(3));
		}
		System.out.println("请输入您的答案:");
		Scanner scanner = new Scanner(System.in);
		String userInput = scanner.next();
		int u = userInput.charAt(0) - 'A';
		if (u==rightOption) {
			System.out.println("恭喜您答对了!");
		} else {
			System.out.println("恭喜您答错了!");
			System.out.println("正确答案是"  + (char)('A' + rightOption));
		}
	}
}

输出: 白?依山尽 黄?入海流 欲?千里目 ?上一层楼 A. 日, 河, 穷, 更 B. 穷, 日, 更, 河 C. 日, 更, 穷, 河 D. 河, 日, 更, 穷 请输入您的答案:

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。