關于猜字符的小程序
主要實現:隨機輸出5個字母,用戶輸入猜測的字母,進行對比得出結果
主要有3個方法:主方法main();
產生隨機字符的方法generate();
比較用戶輸入的字符與隨機產生的字符的方法check();
主要的數據:char[] chs;? //保存隨機產生的字符數組
char[] input;? //保存用戶輸入的字符數組
???????????????? count ;????????? //保存猜測的錯誤次數
score;?????????? //保存分數
boolean[] flags;? //開關數組,避免隨機產生相同的字符
int[] result;?? //保存結果
詳細代碼:
1 package com.tedu.demo; 2 3 import java.util.Scanner; 4 5 /* 6 * Guessing類實現猜字符游戲 7 * 1、通過隨機產生字母,用戶輸入猜的字母,進行對比 8 * 2、輸出每次猜測的正確字母,與位置 9 * 3、產生分數 10 * 11 * */ 12 13 public class Guessing { 14 public static void main(String[] args) { 15 Scanner scan = new Scanner(System.in); 16 char[] chs = generate();// 獲取隨機數組 17 System.out.println(chs);//作弊 18 19 int count = 0; 20 21 22 while (true) { 23 System.out.println("請輸入你猜測得字符:"); 24 String str = scan.next().toUpperCase();//接收用戶輸入的字符,并將小寫轉換為大寫 25 if(str.equals("EXIT")){ 26 System.out.println("下次再猜吧!!!"); 27 break; 28 } 29 char[] input = str.toCharArray(); // 將字符串轉換為字符數組; 30 31 int[] result = check(chs, input); // 獲取用戶輸入的字符數組與隨機數組的比較結果 32 if (result[0] == chs.length) { 33 int score = 100 * chs.length - 10 * count; 34 System.out.println("猜測正確,得分" + score); 35 break; 36 } else { 37 count++; 38 System.out.println("你猜對了" + result[1] + "個字符,位置對了" + result[0] 39 + "個,猜測錯誤,請繼續猜吧!!!"); 40 41 } 42 } 43 // System.out.println(chs); 44 } 45 46 // 隨機生成字母方法 47 public static char[] generate() { 48 char[] letter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 49 'K', 'L', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 50 'X', 'Y', 'Z' }; 51 char[] chs = new char[5]; 52 // 設置開關數組, 53 boolean[] flags = new boolean[letter.length]; 54 55 for (int i = 0; i < chs.length; i++) { 56 int index; 57 do { 58 // 生成隨機的下標 59 index = (int) (Math.random() * letter.length); 60 } while (flags[index] == true); 61 // 生成的字母就是letter數組隨機下標 62 chs[i] = letter[index]; 63 flags[index] = true; // 把用過的下標的flags值改為true 64 } 65 66 return chs; 67 } 68 69 // 比較用戶輸入的字母與隨機產生字母 70 public static int[] check(char[] chs, char[] input) { 71 int[] result = new int[2]; 72 73 for (int i = 0; i < chs.length; i++) { 74 for (int j = 0; j < input.length; j++) { 75 if (chs[i] == input[j]) { // 判斷字符是否有正確的 76 result[1]++; // 字符正確+1 77 if (i == j) { // 判斷位置是否正確 78 result[0]++; // 位置正確+1 79 } 80 } 81 82 } 83 } 84 return result; 85 } 86 87 }
?