This exercise/program should handle underflow, overflow, divide by zero. Ul leng
ID: 3816669 • Letter: T
Question
This exercise/program should handle underflow, overflow, divide by zero.
Ul length in this chapter. Exercise 10 Create a class Int with the following components: a. A field to store an int value. b. A constructor so that new Int (x) creates an Int object that stores the int value x. c. An instance method toString so that x. tostring returns the value of the Int object x in string form. d. An instance method plus so that x .plus (y) returns a new Int object whose value is the value of the Int x plus the value of the Int y. There should be no side effects. e. Instance methods minus, times, and div, similar to the plus method de scribed above. The div method should perform integer division, like the operator on int values.) f. An instance method isprime so that x.isPrime returns true if the value of the Int x is a prime number.Explanation / Answer
public class Int {
private int x;
public Int(int x) {
this.x = x;
}
@Override
public String toString() {
return this.toString();
}
public Int plus(int x) {
int result = this.x + x;
if (result < Integer.MIN_VALUE) {
throw new RuntimeException("Integer Underflow");
}
if (result > Integer.MAX_VALUE) {
throw new RuntimeException("Integer Overflow");
}
return new Int(result);
}
public Int minus(int x) {
int result = this.x - x;
if (result < Integer.MIN_VALUE) {
throw new RuntimeException("Integer Underflow");
}
if (result > Integer.MAX_VALUE) {
throw new RuntimeException("Integer Overflow");
}
return new Int(result);
}
public Int times(int x) {
int result = this.x * x;
if (result < Integer.MIN_VALUE) {
throw new RuntimeException("Integer Underflow");
}
if (result > Integer.MAX_VALUE) {
throw new RuntimeException("Integer Overflow");
}
return new Int(result);
}
public Int div(int x) {
Int a = null;
try {
a = new Int(this.x / x);
} catch (ArithmeticException e) {
System.out.println("Divide by Zero Error: " + e.toString());
}
return a;
}
public boolean isPrime() {
int num = this.x;
boolean flag = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
flag = false;
break;
}
}
if (flag) {
System.out.println(num + " is a Prime Number");
}
return flag;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.