本篇文章包括
1、寻找最大公因数
2、寻找最小公倍数
3、判断一个数是否是质数
4、整型加法
5、浮点型加法
6、反转数字
package Eg;
/**
* 2023.10.24
* 简单Java语法练习
*/
public class Example1 {
public static void main(String[] args) {
System.out.println("最大公约数:");
System.out.println(gcd(4, 8));
System.out.println("最小公倍数:");
System.out.println(lcm(4, 8));
System.out.println("判断素数:");
System.out.println(isPrime(5));
System.out.println("整型加法:");
add(3, 5);
System.out.println("浮点型加法:");
add(4.7, 6.8);
System.out.println("数字反转:");
reverse(-8865);
}
public static int gcd(int x, int y) {//最大公约数
if (y == 0)
return x;
return gcd(y, x % y);
}
public static int lcm(int x, int y) {//最小公倍数
return x * y / gcd(x, y);
}
public static boolean isPrime(int x) {//判断一个数是否是质数
if (x == 1)
return false;
for (int i = 2; i < x; i++) {
if (x % i == 0)
return false;
}
return true;
}
public static void add(int x, int y) {//整型加法
System.out.println(x + y);
}
public static void add(double x, double y) {//浮点型加法保留两位小数
System.out.printf("%.2f", x + y);
}
public static void reverse(int n) {//反转数字
if (n > 0) {
StringBuilder str = new StringBuilder();//创建一个StringBuilder类
str.append(n);//将数加到StringBuilder类里
StringBuilder str1 = str.reverse();//将字符串反转
int m = Integer.valueOf(String.valueOf(str1));//将StringBuilder类转换成String类,再转换成int类型
System.out.println(m);
} else {
String str = n + "";
String str1 = str.substring(1);
StringBuilder sb = new StringBuilder();
sb.append(str1);
String str2 = sb.reverse().toString();
int m = -Integer.valueOf(str2);
System.out.println(m);
}
}
}
结果:
最大公约数:
4
最小公倍数:
8
判断素数:
true
整型加法:
8
浮点型加法:
11.50数字反转:
-5688
Process finished with exit code 0