constructor – Calculating the area of a circle in Java – Win Mundo 您所在的位置:网站首页 RegSvr32 constructor – Calculating the area of a circle in Java – Win Mundo

constructor – Calculating the area of a circle in Java – Win Mundo

2023-04-05 03:00| 来源: 网络整理| 查看: 265

constructor – Calculating the area of a circle in Java

You should have a method calculate area based on the current radius. Area should not be set.

public class Circle { private double radius; public Circle() { radius = 0; } public Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public double getArea() { return calculateArea(); } private double calculateArea() { return radius * radius * Math.PI; } public String toString() { return The radius of the circle is: + radius + , and the area is: + calculateArea(); } }

If you did wish to store area in a variable, you should update it when you set the radius. It shouldnt be independently set from setArea. Otherwise, youre vulnerable to inconsistency. Also, a note from Josh Blochs Effective Java. While your toString should take advantage of this calculated area rather than replicating the calculation, you shouldnt have toString call anything in your public API. That would be an issue if, for instance, you overrode getArea, which would mean it would behave differently than your Circle.toString expects. Thats why I put the private calculateArea in there.

Pass radius instead of area in the setArea method:

public void setArea( double radius ) { area = (radius)*(radius)*Math.PI; }

for complete code- http://pastebin.com/jggRrUFd

constructor – Calculating the area of a circle in Java

This is my version of the Circle_Math Class, with entry validation and with the minimum number of lines / operations and memory space to get the job done. Please leave a comment if you want.

public class circle { static double rad; public circle() { rad = 0; } public static void setRad() { Scanner sc = new Scanner(System.in); do { while (!sc.hasNextDouble()) { sc.next();// this code is to skip the exception created } rad = sc.nextDouble(); } while (rad < 0); System.out.println(radius value is: + rad); } public static double getCirclearea() { return rad * rad * Math.PI; } public static double getCircumference() { return 2 * Math.PI * rad; } }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有