+ 2
Your circle area calculation could be the problem.
"width" is a weird term to describe size of a circle. If width = diameter, you have a problem because the formula for area of a circle is PI * radius * radius instead of PI * diameter * diameter.
Try this instead in Circle's area calculation:
double resultcircle = (pi*(width*width) * 0.25);
If your test cases pass with this single line replacement, I should be correct.
If the above change works and you care about clarity of your code, refactor "width" to be in Square but have "radius" or "diameter" in the Circle. Remove "width" from the Shape class because it is too ambiguous at that level of abstraction.
Unrelated to your question, some more minor improvements are:
- remove double pi = Math.PI; from Shape because the Circle class can just reference Math.PI. The extra property is slightly less efficient in memory usage, performance, and more code.
- Remove result and resultcircle from Shape. These are and should continue to be local variables in your Square and Circle area methods. They're not needed by the Shape class.
- Just to be clear with my other points, the area method is the only thing that should remain in the Shape class. There is no need to maintain any properties there.
- remove import static java.lang.Math.PI; since it is redundant. java.lang is a unique package because it is always imported without you writing an import statement. As a result, "Math.PI" will work whether you import java.lang or not.
- I can't think of a reason to change this so this point is just for your information. Square and Circle could be defined outside of your public class Program like you've done with Shape. Shape could also be defined as a static class within class Program.
+ 1
Here is the code applying all of my recommendations from a previous answer:
import java.util.Scanner;
abstract class Shape {
abstract void area();
}
public class Program {
public static void main(String[ ] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
Square a = new Square(x);
Circle b = new Circle(y);
a.area();
b.area();
}
static class Square extends Shape{
private int width;
public Square(int width) {
this.width =width;
}
void area() {
int result = (width*width);
System.out.println(result);
}
}
static class Circle extends Shape{
private int diameter;
public Circle(int diameter) {
this.diameter = diameter ;
}
void area() {
double resultcircle = (Math.PI*(diameter*diameter) * 0.25);
System.out.println(resultcircle);
}
}
}



