"1. Write a method that accepts a number as input and prints whether the number is odd or even using an if/else statement as well as a ternary expression."
and wrote the following code to accommodate any number, with and without a floating point.
I tried using parameter type Number (as well as Object) to avoid method overload, but the compiler did not like the fact that in the first if, num was Number/Object type and 2 was int. Then I tried final Number n = 2; if (num%n == 0) and the compiler complained about both being Number type!
Questions:
1. Why would the compiler complain about bad operand types, if both num and n are Number types?
2. Is there a parameter type that can handle all types of numbers or overloading is the only way?
Thanks
p.s. I think the intent of the exercise 4 of the same page would have been a lot more clear if the first if statement were if (a == b){ instead of if (a == b) and a little further down, the code were else if (flag == false){ instead of else if (flag == false).
Code: Select all
public class Chapter6 {
public void whichNumber(long num){
if (num%2 == 0)
System.out.println(num+" is an even number.");
else
System.out.println(num+" is an odd number.");
System.out.println(num%2 == 0? num+" is an even number." : num+" is an odd number.");
}
public void whichNumber(double num){
if (num%2 == 0)
System.out.println(num+" is an even number.");
else
System.out.println(num+" is an odd number.");
System.out.println(num%2 == 0? num+" is an even number." : num+" is an odd number.");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Chapter6 t = new Chapter6();
t.whichNumber(5.0f);
t.whichNumber(244);
t.whichNumber(6.5);
t.whichNumber(2147483649L);
}
}