简单的Java语法练习

本篇文章包括

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值