• 手把手教你猜字小游戏


    package test07;
    import java.util.Scanner;
    //猜字符游戏
    public class Guessing {
    //主方法
    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.nextLine().toUpperCase(); //接收用户输入的字符串并转换为大写字母
    if(str.equals("EXIT")) { //判断字符串内容是否是EXIT
    System.out.println("下次再来吧!");
    break;
    }
    char[] input = str.toCharArray(); //将字符串转换为字符数组
    int[] result = check(chs,input); //对比:随机字符数组与用户输入的字符数组
    if(result[0]==chs.length) { //对
    int score = 100*chs.length-10*count; //1个字符100分,猜错一次扣10分
    System.out.println("恭喜你猜对了,得分为:"+score);
    break; 
    }else { //错
    count++; //猜错次数增1
    System.out.println("字符对个数为:"+result[1]+",位置对个数为:"+result[0]);
    }
    }
    }

    //生成随机字符数组chs
    public static char[] generate() {
    char[] chs = new char[5]; //随机字符数组
    char[] letters = { '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[letters.length]; //标记数组
    for(int i=0;i<chs.length;i++) { //遍历随机字符数组
    int index;
    do {
    index = (int)(Math.random()*letters.length); //随机下标(0到25之间)
    }while(flags[index]==true); //下标index对应的标记为true,表示对应字符已经使用过,则重新生成index下标
    //下标index对应的标记为false时,表示对应字符未用过,则循环结束
    chs[i] = letters[index]; //基于下标index获取对应的字符并赋值给chs中的每一个元素
    flags[index] = true; //将下标index对应的标记修改为true,表示对应字符已存过
    }
    return chs;
    /*
    * i=0 index=0 chs[0]='A' flags[0]=true
    * i=1 index=25 chs[1]='Z' flags[25]=true
    * i=2 index=0/25/0/1 chs[2]='B' flags[1]=true
    * ...
    */
    }

    //对比:随机字符数组chs与用户输入的字符数组input
    public static int[] check(char[] chs,char[] input) {
    int[] result = new int[2]; //对比结果(0,0)--假设result[1]为字符对,result[0]为位置对
    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元素不再参与比较了
    }
    }
    }
    return result;
    }

    }

  • 相关阅读:
    HTML5学习总结-番外05 http 状态码
    Python开发技巧
    QPushButton class
    Qt class
    QTableWidgetItem class
    毕业设计进度10
    毕业设计进度9
    毕业设计进度8
    毕业设计进度7
    毕业设计进度6
  • 原文地址:https://www.cnblogs.com/xingsir/p/11947438.html
Copyright © 2020-2023  润新知