1.逗号操作符(不是逗号分隔符),唯一使用到的地方是for循环的控制表达式。可初始化多个变量,但是它们必须有相同的类型。
// 逗号操作符的使用:
for (int i = 0, j = i; i < 25; i++, j+=i) {
System.out.println("i = " + i + " j = " + j);
}
// 等同于:
int j = 0;
for (int i = 0; i < 25; i++) {
j += i;
System.out.println(j);
}
2.switch case语句,一般情况下每个case都需要break以防止case穿透,default为未找到case时默认执行语句。(有时也会利用穿透来为一段代码形成多重匹配,只要符合多重条件中的一种,就执行那段特别的代码,然后再break。)
Random rand = new Random(47);
int i = rand.nextInt();
int f = rand.nextInt();
switch (i / f) {
case 1:
System.out.println("不要括号?");
System.out.println("真不要括号?");
break;
case 2:
System.out.println("真真不要括号?");
break;
default:
System.out.println("默认");
}
3.吸血鬼数字(四位数,可拆分成两个两位数的乘积,其中两个两位数的数字来自于四位数,且不能重复使用,以两个0结尾的数字是不允许的)
/* 运行结果:
1395 15 * 93
1260 21 * 60
1827 21 * 87
2187 27 * 81
1530 30 * 51
1435 35 * 41
6880 80 * 86
循环次数:243
吸血鬼数量:7
*/
public static void XiXueGui() {
int num = 0; // 循环次数
int count = 0; // 吸血鬼数字个数
for (int i = 11; i < 100; i++) {
for (int j = Math.max((1000 / i) + 1, i); j < 100; j++) { // 设置j比i大,避免重复
int production = i * j;
if (production % 100 == 0 || (production - i - j) % 9 != 0) { // 关键代码
continue;
}
num++;
char[] proArray = String.valueOf(production).toCharArray();
char[] spaArray = (String.valueOf(i) + j).toCharArray();
Arrays.sort(proArray);
Arrays.sort(spaArray);
if (Arrays.equals(proArray, spaArray)) {
count++;
System.out.println(production + " " + i + " * " + j);
}
}
}
System.out.println("循环次数:" + num);
System.out.println("吸血鬼数量:" + count);
}
关键代码说明:假设某吸血鬼数字number为1000a+100b+10c+d,则i和j可以是:10a+b、10c+d或10a+d、10b+c等等。假设i和j分别为10a+d、10b+c,那么number - i - j = 990a+90b+9c = 9*(110a+10b+c) 是9的倍数。其他ij组合也可以得到相同结果。