设计一个名为MyInteger的类。这个类包括1.一个名为value的int型数据域,存储这个对象表示的int值2.一个指定的int值创建MyInteger对象构造方法3.一个返回int值得get方法4.如果值分别为偶数,奇数,素数,那么isEven()isOdd()isprime()方法都会返回ture5.如果该对象的值与指定的值相等,那么equals(int)和equals(MyInteger)方法返回值ture6.静态方法parseInt(Char[])将数字字符构成的数组转换成一个int值7.静态方法parseInt(String)将一个字符串转换成一个int值
时间: 2024-03-01 12:54:52 浏览: 20
好的,以下是MyInteger类的代码实现:
```java
public class MyInteger {
private int value;
public MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean isEven() {
return value % 2 == 0;
}
public boolean isOdd() {
return value % 2 == 1;
}
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 num) {
return value == num;
}
public boolean equals(MyInteger myInt) {
return value == myInt.getValue();
}
public static int parseInt(char[] chars) {
int result = 0;
for (char c : chars) {
if (Character.isDigit(c)) {
result = result * 10 + Character.getNumericValue(c);
} else {
throw new NumberFormatException("Invalid input: " + new String(chars));
}
}
return result;
}
public static int parseInt(String str) {
return parseInt(str.toCharArray());
}
}
```
使用示例:
```java
MyInteger myInt = new MyInteger(7);
System.out.println(myInt.getValue()); // 输出 7
System.out.println(myInt.isEven()); // 输出 false
System.out.println(myInt.isOdd()); // 输出 true
System.out.println(myInt.isPrime()); // 输出 true
System.out.println(myInt.equals(7)); // 输出 true
System.out.println(myInt.equals(8)); // 输出 false
MyInteger anotherInt = new MyInteger(7);
System.out.println(myInt.equals(anotherInt)); // 输出 true
System.out.println(MyInteger.parseInt(new char[] {'1', '2', '3'})); // 输出 123
System.out.println(MyInteger.parseInt("456")); // 输出 456
```