Random rand = new Random();
String[] ArithmeticSign = { "+", "-", "" };
for(int n = 0;n<10;n++) {
while (true) {
String num = "1";
for (int i = 2; i < 10; i++) {
int a = rand.nextInt(3) + 1;// 范围是1,2,3
num = num + ArithmeticSign[a - 1] + i;// 数组下标从0开始因为随机数里没有0所以要减1
}
int sum = 0;
Pattern p = Pattern.compile("^\\d*");//获取第一个数字
Matcher m = p.matcher(num);
while (m.find()) {
sum += Integer.parseInt(m.group());
}
p = Pattern.compile("\\+([0-9]*)");//获取正数
m = p.matcher(num);
while (m.find()) {
sum += Integer.parseInt(m.group());
}
p = Pattern.compile("\\-([0-9]*)");//获取负数
m = p.matcher(num);
while (m.find()) {
sum += Integer.parseInt(m.group());
}
if (sum == 100) {
System.out.println(num + "=" + sum);
break;
}
}
}