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