001 三目运算
三目运算符是if…else条件语句的简写格式,可以完成简单的条件判断,在javaScript用的更加广泛但Java也可以方便使用哦
package com.company;
public class 三元运算符 {
public static void main(String[] args) {
System.out.println(55 % 2 == 0? "偶数": "奇数");
}
}
002 两个变量互换(不借助第三个变量)
异或和其他运算符不会改变变量本身值,即a^b没有任何意义
package com.company;
public class 两个变量互换不借助第三个变量 {
public static void main(String[] args) {
int a = 1;
int b = 2;
a = a^b;
b = b^a;
a = a^b;
System.out.println("a=" + a + "\n" + "b=" + b);
}
}
003 根据用户消费打折业务逻辑
规避负数带来的错误
package com.company;
public class 根据用户消费打折业务逻辑 {
public static void main(String[] args) {
float money = 2022;
float rebate = 0f;
if (money > 200) {
int grade = (int) money / 200;
switch (grade) {
case 1:
rebate = 0.95f;
break;
case 2:
rebate = 0.90f;
break;
case 3:
rebate = 0.85f;
break;
case 4:
rebate = 0.83f;
break;
case 5:
rebate = 0.80f;
break;
case 6:
rebate = 0.78f;
break;
case 7:
rebate = 0.75f;
break;
case 8:
rebate = 0.73f;
break;
case 9:
rebate = 0.70f;
break;
case 10:
rebate = 0.65f;
break;
default:
rebate = 0.60f;
}
}
System.out.println("您的累计消费金额为:" + money);
System.out.println("您将享受" + rebate + "折优 优惠!");
}
}
执行结果如下:
004 杨辉三角
杨辉三角形由数字排列,可以把它看作一个数字表,其基本特性是两侧数值均为1,其他位置的数值是其正上方的数值与左上角数值之和。
package com.company;
public class 杨辉三角 {
public static void main(String[] args) {
int[][] triangle = new int[8][];
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
for (int j = 0; j <= triangle[i].length - 1; j++) {
if (i == 0 || j == 0 || j == triangle[i].length - 1) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i - 1][j] + triangle[i - 1][j - 1];
}
System.out.print(triangle[i][j] + "\t");
}
System.out.println();
}
}
}
执行结果如下:
005 九九乘法表
package com.company;
public class 九九乘法表005 {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "*" + i + "=" + i * j + "\t");
}
System.out.println();
}
}
}
|