在控制台进行操作,还没实现界面化
package guessGame;
import java.util.*;
import java.io.*;
public class GuessDigit {
private ArrayList<Integer> digitArray ;
private boolean flag = true;
private static final int SIZE = 4;
private static int count = 7;
public GuessDigit(){
this(GuessDigit.count);
}
public GuessDigit(int count){
GuessDigit.count = count;
digitArray = new ArrayList<Integer>(SIZE);
Random r = new Random();
int n = 0;
while(n < SIZE){
int i = r.nextInt(10);
if(!digitArray.contains(i)){
digitArray.add(n, i);
n ++;
}
}
System.out.println("请输入4个不同的数字,你一共有"+count+"次机会:");
}
public String toString(){
String s = "";
for(int i = 0; i < digitArray.size(); i ++){
s += digitArray.get(i);
}
return s;
}
private void campare(String s){
String array = toString();
int A = 0, B = 0;
char c1, c2;
for(int i = 0 ;i < SIZE; i ++){
c1 = array.charAt(i);
c2 = s.charAt(i);
if(c1 == c2){
A ++;
}else if(array.indexOf(c2) != -1)
B ++;
}
System.out.println(s + " " + A + "A" + B + "B");
if(A == SIZE){
System.out.println("恭喜你猜对了!数字是" + this);
flag = false;
}
if(--count == 0 && A < SIZE ){
System.out.println("已达到规定次数,数字是:"+this);
flag = false;
}
}
public void getConsole() throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s ;
boolean repeat;
int i;
while(flag){
s = stdin.readLine();
repeat = false;
i = 0;
if(s.matches("//d{4}")){
while(!repeat && i < SIZE-1){
if(s.lastIndexOf(s.charAt(i)) != i){
System.out.println("请输入4不同的数字:");
repeat = true;
}
i ++;
}
if(!repeat)
campare(s);
}else
System.out.println("请检查输入值的格式:");
}
}
public static void main(String[] args) throws IOException {
GuessDigit g = new GuessDigit(); ;
//System.out.println(g);
g.getConsole();
}
}