java语言的猜数字游戏代码

来源:互联网 发布:淘宝宝贝发布时间 编辑:程序博客网 时间:2024/06/05 01:18

昨天写的一段乱七八糟的java语言猜数字代码。

====================================

系统随机生成0-9中的不重复四位数字。

然后用户输入四个数字

如果数字对了,位置不对 则显示 nB,n是有几个是位置对的。

如果数字对了,位置也是对的 则显示mA,m代表有几个数字是正确位置上的。

例如:  生成的是0369    用户输入的是0396 则显示2A2B,两个位置是正确并且数字正确的,另外两个是数字正确,位置不正确的。

======================================

package com.example.test;import java.util.Random;import java.util.Scanner;public class NumberCode {int[] Nums = new int[4];int[] inputNumsArray = new int[4];int difficultyLevel;int difficulty;int aA = 0;int bB = 0;String numberStr = "";String str = "";/** * 生成随机数 */public int[] randNums(int n) {for (int i = 0; i < Nums.length; i++) {Random ran = new Random();int a = ran.nextInt(10);if (i - 1 != -1) {for (int j = 0; j < i; j++) {if (a == Nums[j]) {i--;break;} else {Nums[i] = a;}}} else {Nums[i] = a;}}return Nums;}/** * 选择游戏难度  */public int selectLevel() {// 接受一个数字// 1:Easy 可以猜12次// 2:Common 可以猜9次// 3:Hard 可以猜7次Scanner scan = new Scanner(System.in);System.out.println("请选择难度系数(输入数字),1:Easy 可以猜12次;2:Common 可以猜9次;3:Hard 可以猜7次");difficulty = scan.nextInt();switch (difficulty) {case 1:difficultyLevel = 12;break;case 2:difficultyLevel = 9;break;case 3:difficultyLevel = 7;break;default:break;}return difficultyLevel;}/** * 接受用户输入的数字 */public int[] inputNums(int n) {Scanner scan = new Scanner(System.in);int b = scan.nextInt();for (int i = 0; i < inputNumsArray.length; i++) {int c = (int) ((int) b / Math.pow(10, 3 - i));inputNumsArray[i] = c;b = (int) (b - c * Math.pow(10, (3 - i)));}return inputNumsArray;}/** * 数字比对的方法 */public String compare(int[] answer, int[] inputs) {for (int i = 0; i < answer.length; i++) {if (inputs[i] == answer[i]) {aA += 1;continue;} else {for (int j = 0; j < answer.length; j++) {if (inputs[i] == answer[j]) {bB += 1;}}}}str = "" + aA + "A " + bB + "B ";return str;}/** * 整个游戏过程代码  */public void play() {randNums(4);for (int i = 0; i < Nums.length; i++) {numberStr = numberStr + Nums[i];}selectLevel();System.out.println("你选择了难度系数:" + difficulty + " 共有:" + difficultyLevel+ "次机会。");for (int i = 0; i < difficultyLevel; i++) {inputNums(4);int chanceNums = difficultyLevel - i - 1;compare(Nums, inputNumsArray);if (aA != 4) {if (chanceNums == 0) {System.out.println("机会用完了,答案是:" + numberStr);break;} else {System.out.println(str + " 你还有" + chanceNums + "次机会");}aA = 0;bB = 0;} else if (aA == 4) {System.out.println("恭喜你,答对了");break;}}}public static void main(String[] args) {NumberCode a = new NumberCode();a.play();}}


0 0