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 <= 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) {
// Test MyInteger(int x) constructor and getInt() method
MyInteger num1 = new MyInteger(5);
System.out.println('num1: ' + num1.getInt()); // Output: num1: 5
// Test isEven() method
System.out.println('num1 is even: ' + num1.isEven()); // Output: num1 is even: false
// Test isOdd() method
System.out.println('num1 is odd: ' + num1.isOdd()); // Output: num1 is odd: true
// Test isPrime() method
System.out.println('num1 is prime: ' + num1.isPrime()); // Output: num1 is prime: true
// Test equals(int x) method
System.out.println('num1 equals 5: ' + num1.equals(5)); // Output: num1 equals 5: true
System.out.println('num1 equals 6: ' + num1.equals(6)); // Output: num1 equals 6: false
// Test parseInt(String x) method
String str = '12345';
int num2 = MyInteger.parseInt(str);
System.out.println('num2: ' + num2); // Output: num2: 12345
}
}
原文地址: http://www.cveoy.top/t/topic/mI92 著作权归作者所有。请勿转载和采集!