首页 > 代码库 > 猜数字游戏

猜数字游戏

package com.lovo.homework;

import java.util.Scanner;

public class GuessGame {

private int[] backNum = new int[4];

private int[] inputNum = new int[4];

//主控方法
public void run(){
this.autoGenerate();
for(int i = 0; i < 7; i++){
System.out.println("第" + (i + 1) + "次猜测:");
this.inputNumber();
String result = this.compare();
System.out.println("您本次猜测的结果是:" + result);
if(result.equals("4A0B")){
System.out.println("恭喜,恭喜。天才!!");
break;
}else if(i == 6){
System.out.print("可惜了.....结果是:");
this.showBackNum();
}
}

}


//作弊方法
private void showBackNum(){
for(int i = 0; i < 4; i++){
System.out.print(this.backNum[i]);
}
System.out.println();
}

//生成后台数
private void autoGenerate(){
for(int i = 0; i < this.backNum.length; i++){
this.backNum[i] = (int)(Math.random() * 10);
for(int j = 0; j < i; j++){
if(this.backNum[i] == this.backNum[j]){
i--;
break;
}
}
}
}

//接收输入
private void inputNumber(){
while(true){
System.out.println("请输入一个四位数:");
int input = new Scanner(System.in).nextInt();
if(input < 100 || input >= 10000){
System.out.println("输入有误,请保证输入的是一个每不重复的四位数");
continue;
}

this.inputNum[0] = input / 1000;
this.inputNum[1] = input / 100 % 10;
this.inputNum[2] = input / 10 % 10;
this.inputNum[3] = input % 10;

boolean flag = this.examInput();
if(flag){
break;
}
}

}

//校验输入重复位
private boolean examInput(){
for(int i = 1; i < this.inputNum.length; i++){
for(int j = 0; j < i; j++){
if(this.inputNum[i] == this.inputNum[j]){
System.out.println("您输入的数中有相同位,请重新输入");
return false;
}
}
}
return true;
}

private String compare(){
String result = "";
int numA = 0;
int numB = 0;
for(int i = 0; i < this.inputNum.length; i++){
for(int j = 0; j < this.backNum.length; j++){
if(this.inputNum[i] == this.backNum[j] && i == j){
numA ++;
}else if(this.inputNum[i] == this.backNum[j]){
numB ++;
}
}
}
result = numA + "A" + numB + "B";
return result;
}


}

猜数字游戏