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

72 lines
1.7 KiB
Java

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() {
// This is an explicit narrowing typecast from double to int
return (int) value % 2 == 0;
}
public boolean isPrime() {
if (value <= 1 || value != (int) value) return false;
for (int i = 2; i <= Math.sqrt(value); i++) if (
(int) value % i == 0
) return false;
return true;
}
public boolean isArmstrong() {
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;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
Number number = new Number(sc.nextDouble());
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()
);
sc.close();
}
}