只会for循环?某山打字小游戏也能玩的转!

很多小伙伴,在刚刚接触Java循环时,肯定做过很多例如打星星,求500以内的质数等小题目,但是各位有没有想过for循环加上数组,也能实现简单的打字小游戏。

下面我们来看看具体的Java代码:

import java.util.Random;
import java.util.Scanner;
public class Game {
    public static void main(String[] args) {
        Random rand = new Random();
        Scanner input = new Scanner(System.in);
        int correctInputCount = 0; //记录正确的符号数
        final int Rows = 5,COLS = 10;   //行数和每行列数(每行字符的数量)
        char[] randCs = new char[COLS];
        char t;
        char[] inputS;//存储用户输入的字符串

        long begin = System.currentTimeMillis(); //获取系统当前时间的毫秒数
        //控制输入和输出的行数
        for (int i = 1; i <=Rows ; i++) {
            //生成一行符号
            for (int j = 0; j <COLS ; j++) {
                t =(char)(33+rand.nextInt(94));
                //System.out.println(t);
                randCs[j] = t; //将随机生成的字符存入数组的j下标
                System.out.print(t);
            }
            System.out.println();
            //输入
            inputS = input.next().toCharArray();
            //输入正确符号数量统计
            for (int j = 0; j < (randCs.length<inputS.length ? randCs.length:inputS.length) ; j++) {
                if(randCs[j]==inputS[j]){
                    correctInputCount++;
                }
            }
        }
        double end = System.currentTimeMillis();
        //结果展示
        System.out.println("耗时:"+((end-begin)/1000)+"秒");
        System.out.println("正确率:"+(correctInputCount*100.0/(Rows*COLS)));
        
    }
}

是不是很好玩?在下面评论区给出你的成绩吧,看看谁是第一名!

你可能感兴趣的:(Java)