0
What is wrong with this program?
interface shape{ int r=5; double pi=3.14; int h=2; void display(); } class sphere implements shape { public void display() { double x=(4/3)*pi*(r^3); System.out.println("The volume of the sphere is=" +x); } } class cone implements shape { public void display() { double z=(1/3)*pi*(r^2)*h; System.out.println("The volume of the cone is="+z); } } public class interf { public static void main(String args[]) { sphere obj=new sphere(); obj.display(); cone obj1=new cone(); obj1.display(); } }
1 Answer
+ 2
^ is a bitwise XOR operator, which returns bit by bit OR of input values. [https://www.geeksforgeeks.org/operators-in-java/#Bitwise%20Operators] You should use Math.pow(r, 3) for sphere and Math.pow(r, 2) for cone. Remove the XOR ( ^ ) operator.
One more thing, 1/3 gives result in integer, make either the numerator or denominator a double: 1.0/3 or 1/3.0 to get a good result and not always 0. ^^