猜数字小游戏

package day06;
import java.util.Scanner;
public class GussingName {
public static void main(String[] args) {
//主方法
Scanner scan=new Scanner(System.in);
char[] chs=generate();
System.out.println(chs);//作弊
int count=0;//猜错次数
while(true) {//自造死循环
System.out.println(“猜吧!”);
String str=scan.next().toUpperCase();//获取用户输入的字符串,并转换成大写字母
if(str.equals(“EXIT”)) {
System.out.println(“下次再来吧!”);
}
char[] input=str.toCharArray();
int[] result=check(chs,input);
if(result[0]==chs.length) {
int score=100chs.length-10count;
System.out.println(“恭喜你,猜对了,的分为:”+score);
break;
}else {
count++;
System.out.println(“字符对个数:”+result[1]+“位置对个数:”+result[0]);
}
}

}		

//随机生成字符数组
public static char[] generate(){
	char[] chs=new char[5];
	char[] letters= {'A','B','C','D','E','F','G','H',
			'I','J','K','L','L','M','N','0','P','Q',
			'R','S','T','U','V','W','X','Y','Z'};//字符可选范围
	boolean[] flags=new boolean[letters.length];//开关数组,默认为false
	for(int i=0;i<chs.length;i++) {//遍历随机字符数组
		int index;//随机下标
		do{
			index=(int)(Math.random()*26);//生成一个随机下标
		 }while(flags[index]==true); //若下标对应的开关为true时,表示已存过则重新生成index
		                             //若下标对应的开关为false时,表示未存过,条件为假,循环结束
		chs[i]=letters[index];//基于index下标去letters中获取数据,并赋值给chs中的每一个元素
	    flags[index]=true;//修改index下标对应的开关,表示已存过
  }
	    return chs;

}
//对比:随机字符数组与用户输入的字符数组
public static int[] check(char[] chs,char[] input) {
int[] result=new int[2];//对比结果,result[0]为位置对result[1]为字符对
for(int i=0;i<chs.length;i++) {
for(int j=0;j<input.length;j++) {
if(chs[i]input[j]) {//字符对
result[1]++;//字符对个数增1
if(i
j) {//位置对
result[0]++;//位置对个数增1
}
break;//与input字符匹配后,input的其余字符不在参与比较
}
}
}
return result;
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值