规则:猜一个由5个不区分大小写的26个英文字符随机组成的字符数组(5个字符里面不能有重复),具体猜字符的两方面,字符个数对的个数和字符位置也对的个数,总分500分,猜错一次扣10分,强行退出用“EXIT”或exit。
https://blog.csdn.net/weixin_43188836/article/details/120923739
这个跟你要求的基本一样,可以参考一下
楼上的大佬已经公布答案了,基本可用。
设计思路和方法:
1.会用到如下几个变量
1)char[] chs ;//用户随机生成的字符数组
2)char[] input;//用户输入的字符数组
3)int score;//计算得分
4)int[] result;//用来存储字符对的个数和位置对的个数
2.需要如下几个方法:
1)main方法
2)public static char[] generate(){ } 用来生成随机字符的一个方法 ,并返回
3)public staic int[] check(char[] chs,char[] input){ }//用来比较随机生成与用户输入的符,并返回一个数组。
参考代码:
import java.util.Random;
import java.util.Scanner;
public class GuessGame {
public static void main(String[] args) {
char[] chs = generate();
System.out.println(chs);
String str = new String();
Scanner scan = new Scanner(System.in);
int score=100;
int count=0;
while(true){
System.out.println("猜吧!");
str = scan.next().toUpperCase();//将字符串转换为大写
if(str.equals("EXIT")){
System.out.println("下次再来吧!");
break;
}
char[] input = str.toCharArray();//将字符串转换为字符数组
//result[0]代表位置对的个数,count[1]代表对应字母对的个数
int[] result = check(chs,input);
if(result[0]!=chs.length){
count++;
System.out.println("字符对的个数为:"+result[1]+",位置对的个数为:"+result[0]);
}else{
System.out.println("恭喜你猜对了!共得"+(score*chs.length-count*10));
break;
}
}
}
//进行随机生成五个字符
public static char[] generate(){
char[] letter = {'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'};
boolean[] flags = new boolean[letter.length];
char[] chs = new char[5];
Random rand = new Random();
int x;
for(int i=0;i<chs.length;i++){
do{
x = rand.nextInt(letter.length);
}while(flags[x]);
flags[x] = true;
chs[i] = letter[x];
}
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<chs.length;j++){
if(chs[i] == input[j]){
result[1]++;
if(i==j){//位置对是以字母对为前提
result[0]++;
}
break;
}
}
}
return result;
}
}