MIT-Curricular/OOP/Java/Lab/Week5/Number.java

72 lines
1.7 KiB
Java
Raw Permalink Normal View History

2024-09-02 00:08:48 +05:30
import java.util.Scanner;
class Number {
private double value;
public Number(double value) {
this.value = value;
}
public boolean isZero() {
return value == 0;
}
public boolean isPositive() {
return value > 0;
}
public boolean isNegative() {
return value < 0;
}
public boolean isOdd() {
return (int) value % 2 != 0;
}
public boolean isEven() {
2024-09-02 02:51:28 +05:30
// This is an explicit narrowing typecast from double to int
2024-09-02 00:08:48 +05:30
return (int) value % 2 == 0;
}
public boolean isPrime() {
2024-09-02 01:25:58 +05:30
if (value <= 1 || value != (int) value) return false;
for (int i = 2; i <= Math.sqrt(value); i++) if (
(int) value % i == 0
) return false;
2024-09-02 00:08:48 +05:30
return true;
}
public boolean isArmstrong() {
2024-09-02 01:25:58 +05:30
if (value != (int) value) return false;
int num = (int) value, sum = 0, digits = String.valueOf(num).length();
for (int n = num; n > 0; n /= 10) sum += Math.pow(n % 10, digits);
return sum == num;
2024-09-02 00:08:48 +05:30
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
2024-09-02 01:25:58 +05:30
Number number = new Number(sc.nextDouble());
2024-09-02 00:08:48 +05:30
2024-09-02 02:51:28 +05:30
System.out.println(
"Is Zero: " +
number.isZero() +
", Is Positive: " +
number.isPositive() +
", Is Negative: " +
number.isNegative() +
", Is Odd: " +
number.isOdd() +
", Is Even: " +
number.isEven() +
", Is Prime: " +
number.isPrime() +
", Is Armstrong: " +
number.isArmstrong()
);
2024-09-02 00:08:48 +05:30
sc.close();
}
}