import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
private String password = "";
private Scanner sc;
private int numCount = 0;
private int indexCount = 0;
private int count = 0;
/**
* 产生三位数密码
*/
public Test() {
int num = 0;
List<Integer> list = new ArrayList<>();
for (list.size(); list.size() < 3;) {
num = (int) (0 + Math.random() * (9 - 0 + 1));
// 避免重复数字
if (!list.contains(num))
list.add(num);
}
list.forEach(n -> password += String.valueOf(n));
System.out.println(password);
}
public void guess() {
sc = new Scanner(System.in);
String pwd;// 输入猜测的数字
do {
System.out.println("请输入您猜测的密码:");
pwd = input();
count++;
} while (!check(pwd));
System.out.println("恭喜猜中密码,您用了" + count + "次");
sc.close();
}
private String input() {
String str = sc.nextLine();
if (str.length() > 3) {
System.out.println("位数不能超过三位,请重新输入!");
input();
}
if (str.length() < 3) {
System.out.println("位数不能少于三位,请重新输入!");
input();
}
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
System.out.println("只能为数字,请重新输入!");
input();
}
return str;
}
private boolean check(String input) {
if (input.equals(password))
return true;
else {
for (int i = 0; i < input.length(); i++)
for (int j = 0; j < password.length(); j++)
if (input.charAt(i) == password.charAt(j)) {
numCount++;
if (i == j)
indexCount++;
}
if (indexCount != 0)
System.out.println("猜对了" + numCount + "个数字," + indexCount + "个位置正确");
else {
if (numCount == 0)
System.out.println("未猜中!");
else
System.out.println("猜对了" + numCount + "个数字,但位置错误!");
}
}
numCount = 0;
indexCount = 0;
return false;
}
public static void main(String[] args) {
Test test = new Test();
test.guess();
}
}
温馨提示:答案为网友推荐,仅供参考