10.3 (The MyInteger class) Design a class named MyInteger.
The class contains:
■ An int data field named value that stores the int value represented by this object.
■ A constructor that creates a MyInteger object for the specified int value.
■ A getter method that returns the int value.
■ The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd, or prime, respectively.
■ The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the specified value is even, odd, or prime, respectively.
■ The static methods isEven(MyInteger), isOdd(MyInteger), and isPrime(MyInteger) that return true if the specified value is even, odd, or prime, respectively.
■ The methods equals(int) and equals(MyInteger) that return true if the value in this object is equal to the specified value.
■ A static method parseInt(char[]) that converts an array of numeric characters to an int value.
■ A static method parseInt(String) that converts a string into an int value.
函数重载:函数名一样,参数不一样;重载后多了一个功能一样的函数
函数重写:函数名和参数都一样,且重写后覆盖之前函数。
该题重点:
- 重载 isEven, isOdd, isPrime三个函数—判断是否为偶数、奇数、
素数。参数分别为:无参、int、MyInteger
素数的判定:a除以2~sqrt(a)之间任意一个整数,若都除不尽则a为素数。
- 重载 equals函数—判断参数与value是否相等。
参数分别为int、MyInteger - 重载parseInt函数——转换成 int。
参数分别为char[]、String
String 转换成 Int—用 *Integer.valueOf(s)*函数。无需import
- 首先写参数为 int 的函数;
- 无参函数调用前者,参数为 this.value.
- 参数为MyInteger的函数用"."调用。
public static boolean isEven(int value)//value
{
if(value%2==0)
return true;
else
return false;
}
public static boolean isOdd(int value)
{
return !isEven(value);
}
public static boolean isPrime(int value)
{
for(int i=2;i<=Math.sqrt(value);i++)
{
if(value%i==0)
return false;
}
return true;
}
public boolean isEven()//无参
{
return isEven(this.value);
}
public boolean isOdd()
{
return isOdd(this.value);
}
public boolean isPrime()
{
return isPrime(this.value);
}
public static boolean isEven(MyInteger value)//MyInteger
{
return value.isEven();
}
public static boolean isOdd(MyInteger value)
{
return value.isOdd();
}
public static boolean isPrime(MyInteger value)
{
return value.isPrime();
}
- equals类似以上;需注意的是 value—参数;this.value—成员变量
public boolean equals(int value)//equals
{
if(value==this.value)
return true;
else
return false;
}
public boolean equals(MyInteger value)
{
return value.equals(this.value);
}
-
先写参数为String的
Integer类自带的 “valueof(String s)” 可将字符型换成整型。 -
参数为char[]的先化成String,
再调用已经写好的"parseInt(String)"
String s=new String(c); //char->String
public static int parseInt(String s)//parseInt
{
return Integer.valueOf(s);//Integer类
}
public static int parseInt(char[] c)
{
String s=new String(c);//char->String
return Integer.parseInt(s);
}