Java MyInteger 类实现及测试

本文将介绍如何用 Java 编写一个名为 MyInteger 的类,该类表示一个整数,并包含一些常用操作方法。

MyInteger 类代码

public class MyInteger {
    private int value;

    public MyInteger(int x) {
        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 < 2) {
            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);
    }
}

MyInteger 类测试代码

public class MyIntegerTest {
    public static void main(String[] args) {
        MyInteger a = new MyInteger(5);
        MyInteger b = new MyInteger(10);
        MyInteger c = new MyInteger(7);
        MyInteger d = new MyInteger(2);

        System.out.println('a.getInt() = ' + a.getInt());
        System.out.println('b.isEven() = ' + b.isEven());
        System.out.println('c.isOdd() = ' + c.isOdd());
        System.out.println('d.isPrime() = ' + d.isPrime());
        System.out.println('a.equals(5) = ' + a.equals(5));
        System.out.println('MyInteger.parseInt("123") = ' + MyInteger.parseInt("123"));
    }
}

测试结果

a.getInt() = 5
b.isEven() = true
c.isOdd() = true
d.isPrime() = true
a.equals(5) = true
MyInteger.parseInt("123") = 123

代码说明

  1. MyInteger 类包含一个私有成员变量 value,用于存储整数。
  2. 构造方法 MyInteger(int x) 初始化 value
  3. getInt() 方法返回 value 的值。
  4. isEven()isOdd() 方法分别判断 value 是否为偶数和奇数。
  5. isPrime() 方法判断 value 是否为素数。
  6. equals(int x) 方法判断 value 是否等于参数 x
  7. parseInt(String x) 方法将字符串 x 转换为整数。
  8. MyIntegerTest 类包含 main 方法,用于创建 MyInteger 对象并调用其方法进行测试。

通过以上代码,我们可以了解 MyInteger 类的基本功能,并使用 MyIntegerTest 类对其进行测试。在实际应用中,我们可以根据需求扩展 MyInteger 类,添加更多方法,满足不同的需求。

Java MyInteger 类实现及测试 - 整数属性、方法和测试用例

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

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