最近学的猜字符小游戏

        最近,没有记录每天学习情况,我觉得这是一种自我安慰,不如多花时间自己看看笔记本。我想着有好的项目,或者代码,分享给大家更加有意义!

猜字符游戏:

随机获取5个字符

用户输入5个字符

如果用户输入exit   则退出

如果用户输入字符和获取的字符不一样,输出:字符对了几个,位置对了几个

如果用户猜对了,输出得分:共500分 错一次扣10分

package com.atjialiang;

import java.util.Scanner;

//猜字符游戏

public class GuessCharTest {
    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.next().toUpperCase();   
                if (str.equals("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;
                    System.out.println("猜对了,得分:" + score);
                    break;
                }else { 
                        count++;
                        System.out.println("字符对个数:" + result[1] +
                            ",位置对个数:" + result[0]);
                        System.out.println();
                }
            }
      }
        
    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 );
            }while(flags[index] == true);
            chs[i] = letters[index];
            flags[index] = true;
        }
        
        return chs;
    }
    
        //对比
        public static int[] check(char[] chs,char[] input) {
            int[] result = new int[2];
            for(int i = 0; i < chs.length ;i++) {
                for(int j = 0;j < input.length ;j++) {                    
                    if(chs[i] == input[j]) { //字符对
                       result[1]++;
                     if(i == j) { //位置对
                             result[0]++;
                         }
                         break;
                    }
                 }
            }
            return result;
      } 
        
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不摆烂的亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值