0

Why is this java code - solution of course project "figures" is wrong

import java.util.Scanner; import java.lang.Math; abstract class Shape { int width; abstract void area(); } //введите код сюда class Square extends Shape { Square(int a){ this.width = a; } public void area () { System.out.println(this.width*this.width); } } class Circle extends Shape { Circle(int a){ this.width = a; } public void area () { System.out.println(this.width*this.width*Math.PI); } } 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(); } }

4th May 2021, 7:10 PM
Тимур
Тимур - avatar
4 ответов
+ 3
Тимур This should work: public void area(){ System.out.println(Math.PI * width * width); } It is a rounding problem. Here you can read more about floating point numbers and the issues you can get: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
4th May 2021, 7:31 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Thanks. This code was seccessful: import java.util.Scanner; import java.lang.Math abstract class Shape { int width; abstract void area(); } class Square extends Shape { public Square (int width){ this.width = width; } void area(){ width = width * width; System.out.println(width); } } class Circle extends Shape { public Circle (int width){ this.width = width; } void area(){ double widthd = Math.PI * width * width; System.out.println(widthd); } } 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(); } }
4th May 2021, 7:35 PM
Тимур
Тимур - avatar
+ 2
If I'm not wrong, in that challenge you are asked to initialize the base class's attribute width from the child classes' constructor. And in that case you will need to use "super" keyword or maybe not. (think!) Think about it, do you really need "this" keyword for achieving what you want as per the challenge. If suppose you don't know what "super" keyword does then please Google it. I hope this helps!
4th May 2021, 7:20 PM
minirkk
minirkk - avatar
0
import java.util.Scanner; import java.lang.Math; abstract class Shape { int width; abstract void area(); } //введите код сюда class Square extends Shape { Square(int a){ this.width = a; } public void area () { System.out.println(width*width); } } class Circle extends Shape { Circle(int a){ this.width = a; } public void area () { System.out.println(width*width*Math.PI); } } 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(); } }
5th May 2021, 1:48 PM
kreddyt
kreddyt - avatar