package demo;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* 123456789 中间随机添加 “加减符号” 进行运算结果等于100
*
* @author Weirdo-world
*
*/
public class Demo10 {
public static void main(String[] args) {
math();
}
public static void math() {
while (true) {
String[] num = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] sign = { "+", "-", "" };
Random ra = new Random();
int n = 0;
int[] x = { 0, 0, 0 };
// 随机添加 符号
for (int i = 0; i < 3; i++) {
n = ra.nextInt(7) + 1;
for (int j = 0; j < x.length; j++) {
while (x[j] == n) {
j = 0;
n = ra.nextInt(7) + 1;
}
}
x[i] = n;
num[n] = sign[ra.nextInt(3)] + num[n];
}
// 字符数组转换字符串
String str = "";
for (int i = 0; i < num.length; i++) {
str = str.concat(num[i]);
}
int sum = 0;
// 获取第一个数字
Pattern p = Pattern.compile("^\\d*");
Matcher m = p.matcher(str);
if (m.find()) {
sum += Integer.parseInt(m.group());
}
// 查找正号数字
p = Pattern.compile("\\+([0-9]*)");
m = p.matcher(str);
while (m.find()) {
sum += Integer.parseInt(m.group(1));
}
// 查找负号数字
p = Pattern.compile("\\-([0-9]*)");
m = p.matcher(str);
while (m.find()) {
sum -= Integer.parseInt(m.group(1));
}
if (sum == 100) {
System.out.println(str + "=" + sum);
break;
}
}
}
}
随机一个结果:123-45-67+89=100