(MyInteger class) Design a class named MyInteger. The class contains: - An int d
ID: 3531291 • Letter: #
Question
(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 get method that returns the int value.
- Methods isEven(), isOdd(), and isPrime() that return true if the value is even, odd, or prime, respectively.
- Static methods isEven(int), isOdd(int), and isPrime(int) that return true if the specified value is even, odd, or prime, respectively.
- Static methods isEven(MyInteger), isOdd(MyInteger), and isPrime(MyInteger) that return true if the specified value is even, odd, or prime, respectively.
- Methods equals(int) and equals(MyInteger) that return true if the value in the object is equal to the specified value.
- A static method parseInt(String) that converts a string to an int value. Implement the method without using Integer.parseInt(x).
Draw the UML diagram for the class. Implement the class. Write a client program that tests all methods in the class.
Explanation / Answer
public class MyInteger {
int value;
public MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean isEven() {
return (value % 2 == 0) ? true : false;
}
public boolean isOdd() {
return (value % 2 != 0) ? true : false;
}
public boolean isPrime() {
for (int i = 2; i < value; i++) {
if (value % i == 0)
return false;
}
return true;
}
public static boolean isEven(int value) {
return (value % 2 == 0) ? true : false;
}
public static boolean isOdd(int value) {
return (value % 2 != 0) ? true : false;
}
public static boolean isPrime(int value) {
for (int i = 2; i < value; i++) {
if (value % i == 0)
return false;
}
return true;
}
public static boolean isEven(MyInteger myInt) {
return (myInt.value % 2 == 0) ? true : false;
}
public static boolean isOdd(MyInteger myInt) {
return (myInt.value % 2 != 0) ? true : false;
}
public static boolean isPrime(MyInteger myInt) {
for (int i = 2; i < myInt.value; i++) {
if (myInt.value % i == 0)
return false;
}
return true;
}
public boolean equals(int value) {
return (this.value == value) ? true : false;
}
public boolean equals(MyInteger myInt) {
return (this.value == myInt.value) ? true : false;
}
public static int parseInt(String value) {
int i = 0, number = 0;
boolean isNegative = false;
int len = value.length();
if (value.charAt(0) == '-') {
isNegative = true;
i = 1;
}
while (i < len) {
number *= 10;
number += (value.charAt(i++) - '0');
}
if (isNegative)
number = -number;
return number;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.