猜字符(5个字母)
import java.util.Scanner;
public class guessing {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("欢迎来猜字符游戏(总分500.猜错一次扣10分)");
char[] a=generate();
System.out.println(a);
int count=0;
while(true){
String st=sc.nextLine().toUpperCase();
if(st.equals("EXIT")){
System.out.println("欢迎再来");
break;
}
char[] input=st.toCharArray();
int[] result=check(a,input);
if(result[1]==a.length){
int score=100*a.length-count*10;
System.out.println("恭喜您答对,总分"+score);
break;
}else{
count++;
int score=100*a.length-count*10;
System.out.println("答对:"+result[0]+",位置对"+result[1]+";总分:"+score);
}
}
}
public static char[] generate(){//随机生成5个不同的字母
char[] chas=new char[5];
char[] num={'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[num.length];
int index;
for(int i=0; i<chas.length;i++){
do{
index=(int)(Math.random()*26);
}while(flags[index]==true);
chas[i]=num[index];
flags[index]=true;
}
return chas;
}
public static int[] check( char[] cha,char[] input){//嵌套循环比对位置值相同和值相同个数
int[] result=new int [2];
for(int i=0;i<cha.length;i++){
for(int j=0;j<input.length;j++)
{
if(cha[i]==input[j]){
result[0]++;
if(i==j){
result[1]++;
}
break;
}
}
}
return result;
}
}