猜字母游戏
1 package day08_summerize; 2 import java.util.Scanner; 3 import java.util.Random; 4 5 //猜字母游戏 6 /** 7 * @author Jooker 8 * @version v1.0 9 * 10 */ 11 public class GuessCharsGame { 12 13 //method1 生成器:生成1个有n个随机字母元素的数组,元素不重复 14 public char[] arrayChar(int m){ 15 Random rand = new Random(); 16 char[] character = new char[m]; 17 18 for(int n=0;n<m;n++){ 19 character[n] = (char)(rand.nextInt(25)+97); /*随机元素*/ 20 int i = 0; 21 while(i<n){ 22 if(character[n] == character[i]){ /*如果重复,再给该位置的元素赋值,再比较,直到不重复*/ 23 character[n] = (char)(rand.nextInt(25)+97); 24 }else{ 25 i++; 26 } 27 } 28 System.out.print(character[n]); 29 } 30 return character; 31 } 32 33 //method2 比较器:比较随机生成的字母序列和输入的字符串;交互:正确数量、正确位置、猜的次数 34 public boolean check(String in,char[] check,int number,int summerize,boolean treat){ 35 int counter = 0; 36 int position = 0; 37 treat = true; 38 39 for(int n=0;n<number;n++){ 40 for(int i=0;i<in.length();i++){ 41 if(check[n] == in.charAt(i)){ //String1.charAt(i) --从String1字符串里,取出第i个字母 42 counter++; 43 if(n == i){ 44 position++; 45 } 46 } 47 } 48 } 49 50 if((counter == number)&&(position == number)){ 51 System.out.println("恭喜你,都答对了."); 52 treat = false; 53 }else if(in.equals("exit")){ 54 System.out.println("退出游戏"); 55 treat = false; 56 }else{ 57 System.out.println("你猜对了"+counter+"个字母,其中"+position+"个字母位置正确(总次数="+summerize+",exit——退出)"); 58 } 59 60 return treat; 61 } 62 63 public static void main(String[] args){ 64 Scanner scan = new Scanner(System.in); 65 66 //实例化类,再调用方法,生成字母序列 67 System.out.println("欢迎参加猜字母游戏,请输入你想猜测的字母序列元素个数:"); 68 int num = scan.nextInt(); /*输入字母序列个数*/ 69 System.out.println("游戏开始,你猜测的为"+num+"个字母的序列:(exit——退出)"); 70 GuessCharsGame gener = new GuessCharsGame(); 71 72 char[] focus = gener.arrayChar(num); /*调用method1,随机生成字母序列*/ 73 74 //输入字符串 75 int sum = 0; 76 boolean tar =true; 77 while(tar){ 78 String input = scan.next(); 79 sum++; 80 tar = gener.check(input, focus, num, sum, tar); 81 } 82 scan.close(); 83 } 84 }