+ 1
Java Lesson 56 Code Project (Shapes)
I'm quite stumped on this one. I rewrote the code I used twice and still came up with test case #3 being incorrect. It wants the area of a square and area of a circle displayed using inputs that are given to the program at runtime. My area functions are displayed as follows: For the square the line is... System.out.println(width * width); For the circle the line is... System.out.println(Math.PI * (width * width)); It marks test question 1, 2, 4 and 5 as correct, but marks number 3 as wrong. As the test case for #3 is hidden behind a paywall, I have no way to know why it is marking it as incorrect. Anyone have any insight as to why it would mark code that gives the correct output every other time as wrong in that one case? Thanks
6 Réponses
+ 4
Jeremiah
I would say it is a floating point problem.
My code won't work for test case 3 if you calculate width * width * Math.PI
Your parenthesis have the same effect. It calculates first width * width.
+ 4
Yeah, I just typed it out (painfully) on my phone and if I leave the formula as (Math.PI * width * width) without the inner parenthesis it works fine
+ 3
Hello Jeremiah
I am not sure what you did wrong. This code works:
import java.util.Scanner;
abstract class Shape {
int width;
abstract void area();
}
//your code goes here
public class Square extends Shape{
public Square(int width){
this.width = width;
}
public void area(){
System.out.println(width * width);
}
}
public class Circle extends Shape{
public Circle(int width){
this.width = width;
}
public void area(){
System.out.println(Math.PI * width * width);
}
}
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();
}
}
+ 2
That could very well be it. I have a habit of using parenthesis to enforce the order of operations in my mind lol. Unfortunately the website hasn't been loading properly on my computer today so I haven't been able to get back into the lesson. Thanks for your help :)
+ 1
That looks nearly identical to mine, yet is still not working for test case 3... it shouldn't have any bearing on the answer, but ill try removing my inner parenthesis in my circle area formula to see if I'm somehow confusing it
0
Just do this in area method:
double res=Math.PI*(width)*width;
System.out.println(res);