Java MyInteger 类实现:整数操作、奇偶素数判断、字符串转换

本文将介绍如何使用 Java 编写一个名为 MyInteger 的类,用于表示整数并提供一系列操作方法,包括奇偶素数判断、值比较、字符串转换等。

MyInteger 类代码

public class MyInteger {
    private int value;

    public MyInteger(int x) {
        this.value = x;
    }

    public int getInt() {
        return value;
    }

    public boolean isEven() {
        return value % 2 == 0;
    }

    public boolean isOdd() {
        return value % 2 != 0;
    }

    public boolean isPrime() {
        if (value <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(value); i++) {
            if (value % i == 0) {
                return false;
            }
        }
        return true;
    }

    public boolean equals(int x) {
        return value == x;
    }

    public static int parseInt(String x) {
        return Integer.parseInt(x);
    }
}

测试类程序代码

public class MyIntegerTest {
    public static void main(String[] args) {
        MyInteger num1 = new MyInteger(10);
        MyInteger num2 = new MyInteger(11);

        System.out.println('num1 = ' + num1.getInt());
        System.out.println('num2 = ' + num2.getInt());
        System.out.println('num1 is even: ' + num1.isEven());
        System.out.println('num2 is even: ' + num2.isEven());
        System.out.println('num1 is odd: ' + num1.isOdd());
        System.out.println('num2 is odd: ' + num2.isOdd());
        System.out.println('num1 is prime: ' + num1.isPrime());
        System.out.println('num2 is prime: ' + num2.isPrime());
        System.out.println('num1 equals 10: ' + num1.equals(10));
        System.out.println('num2 equals 10: ' + num2.equals(10));
        System.out.println('parseInt("123") = ' + MyInteger.parseInt("123"));
    }
}

运行结果

num1 = 10
num2 = 11
num1 is even: true
num2 is even: false
num1 is odd: false
num2 is odd: true
num1 is prime: false
num2 is prime: true
num1 equals 10: true
num2 equals 10: false
parseInt("123") = 123

代码解释

  1. MyInteger 类

    • 私有成员变量 value 用于存储整数。
    • 构造方法 MyInteger(int x) 用于创建 MyInteger 对象并初始化 value
    • 方法 getInt() 返回 value 的值。
    • 方法 isEven() 判断 value 是否为偶数。
    • 方法 isOdd() 判断 value 是否为奇数。
    • 方法 isPrime() 判断 value 是否为素数。
    • 方法 equals(int x) 判断 value 是否与指定值相等。
    • 静态方法 parseInt(String x) 将数字字符串 x 转换为 int 值。
  2. 测试类程序

    • 创建两个 MyInteger 对象 num1num2,分别存储 10 和 11。
    • 使用 MyInteger 类的方法测试 num1num2 的各种属性和操作结果,并将结果输出到控制台。

通过上述代码,您可以了解 MyInteger 类的基本功能,并根据需要进行扩展和修改,以满足您的编程需求。

Java MyInteger 类实现:整数操作、奇偶素数判断、字符串转换

原文地址: https://www.cveoy.top/t/topic/mJa7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录