Java编程题 —— 猜字母

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

/**
 * 猜字母(大写)
 * 1.根据难度级别随机生成对应个数的大写字母(控制台输入)
 * 控制台输入5,则生成5个大写字母,不能重复,不能排序
 * [A,F,O,E,L],封装方法,char类型
 * 2.用户猜测字母(输入字符串String)
 * ABCDE —— toCharArray()字符数组
 * 比较完成,告诉用户猜对几个字母,猜对位置 2 1
 * 3.输入exit退出游戏 String equals;完全猜对退出游戏
 *
 * 程序运行后,控制台提示用户:
 * 欢迎进来猜字母,输入难度等级
 *
 * 要求:
 * 1.随机生成对应难度个数的大写字母封装方法
 * 2.比较用户与答案封装方法
 * 3.mian方法中测试方法
 *
 */

public class GuessAlp {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("欢迎进来猜字母,输入难度等级: ");
        int level = sc.nextInt();
        char[] right = gen(level);

        System.out.println("答案:"+Arrays.toString(right));
        while (true){
            System.out.println("请输入猜测字母:");
            String s = sc.next();
            if (s.equals("exit")){
                System.out.println("欢迎下次游玩");
                break;
            }
            char[] gues=s.toCharArray();

            int[] diegame = compare(gues, right);
            if (diegame[0]==level&&diegame[1]==level){
                System.out.println("恭喜:"+Arrays.toString(gues));
                break;
            }else{
                System.out.println("猜对"+diegame[0]+"个字母,猜对"+diegame[1]+"位置 ");
            }
        }
    }
    //对应难度级别个数大写字母
    public static char[] gen(int level){
        char[] gues= new char[level];
        Random rd = new Random();
        for (int i = 0; i < level; i++) {
            char a = (char) (rd.nextInt(26)+65);
            boolean b= true;
            for (int j = 0; j < level; j++) {
                if (gues[j]==a){
                    b=false;
                }
            }

            if (b){
                gues[i]=a;
            }
        }
        System.out.println(Arrays.toString(gues));
        return gues;
    }

    //比较输入与答案
    public static int[] compare(char[] gues,char[] right){
        int[] exact=new int[2];
//        int[] place = new int[1];
        int num=0;
        int count=0;
        for (int i = 0; i < right.length; i++) {
            if (gues[i] == right[i]){
//                place[num]=i;
//                place  = Arrays.copyOf(place,place.length+1);
                num++;
            }
            for (int j = 0; j < right.length; j++) {
                if (gues[i]==right[j]){
                    count++;
                    continue;
                }
            }
        }
        exact[0]=count;
        exact[1]=num;

        return exact;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值