Java学习之猜数字小游戏

      今天主要学习了一些初级的设计,完成了这个猜数字的小游戏,其是也算不上是什么游戏,因为我答案都给出来了。当然也是想对代码更加熟练的操作,让自己能够得心应手。

      这个小程序中让我花了点时间的主要是那个如何去重的问题,当时也是思考良久,后来才考虑到使用死循环让随机数产生直到不重复为止,其他感觉也还好。

import java.util.Scanner;

public class GuessingGames {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		char[] chs=generate();
		System.out.println(chs);
		int score=500;
		while(true) {
			System.out.println("请猜猜看!");
			String str=in.next();
			char[] input=str.toCharArray(); //将用户输入的字符串转换为数组
			int[] result=compare(chs, input);
			if (result[1]==chs.length) {
				System.out.println("恭喜你,猜对了!!!你获得的分数为"+score+"猜错次数为:"+(500-score)/10);
				break;
			}else {
				System.out.println("字符猜对个数为:"+result[0]+","+"位置猜对为:"+result[1]);
				score-=10;
			}
		}
	}

	// 随机生成字母
	public static char[] generate() {
		char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
				'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
		char[] chs = new char[5];
		char copy;
		for (int i = 0; i < chs.length; i++) {
			chs[i] = letters[(int) (Math.random() * 26)];
			copy=letters[(int) (Math.random()*26)];
			for (int j = 0; j < i; j++) {
				if (chs[i]==chs[j]) {
					for(;;) {
						copy=letters[(int) (Math.random()*26)];
						if (chs[i]!=copy) {
						chs[i]=copy;
						break;
						}
					}
				}
			}
		}
		return chs;
	}
	
	//完成两个数组的对比
	public static int[] compare(char[] chs,char[] input) {
		int[] score=new int[2];
		for (int i = 0; i < input.length; i++) {
			for (int j = 0; j < chs.length; j++) {
				if (input[i]==chs[j]) {
					score[0]++;
					if (i==j) {
						score[1]++;
					}
					break;
				}
			}
		}
		return score;
	}
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值