Can't display the proper value [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have these classes:
interface Shape
{
public double getPerimeter();
public double getArea();
public void getDetails();
}
and
class Circle implements Shape
{
private double PI = 3.14;
private int radius;
double perimeter, area;
//constructor
public Circle(int radius)
{
perimeter = 2.0 * (PI * radius);
area = PI * (radius * radius);
}
public int getRadius()
{
return radius;
}
public double getPerimeter()
{
return perimeter;
}
public double getArea()
{
return area;
}
public void getDetails()
{
System.out.println("Shape Type: Circle " + "\n"
+ "Radius: " + getRadius() + "\n"
+ "Perimeter: " + getPerimeter() + "\n"
+ "Area: " + getArea() + "\n" );
}
}
and finally
public class TestShape
{
public static void main(String args[])
{
for(int i = 0; i < args.length; i++)
{
try
{
Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe)
{
System.err.print("wrong");
}
catch(IllegalArgumentException iae)
{
System.err.print("wrong");
}
if(args.length==1)
{
i = Integer.parseInt(args[0]);
Circle r1 = new Circle(i);
r1.getDetails();
}
}
}
}
We were assigned to input 1,2 or 3 numbers on the command line of the terminal and the output would display what kind of shape it is depending on the array size. I managed to get the proper parameter and area when I input a number but the radius keeps displaying 0 instead of the actual number I inputted.
This is what the output looks like
So what do you guys think?

You are not assigning the radius in the constructor of Circle...
public Circle(int radius)
{
perimeter = 2.0 * (PI * radius);
area = PI * (radius * radius);
this.radius = radius // this statement is missing
}
Therefore, circle.getRadius() always returns the uninitialized default int value 0.

In your constructor:
public Circle(int radius)
{
perimeter = 2.0 * (PI * radius);
area = PI * (radius * radius);
}
radius refers to the parameter radius, not the radius field declared in Circle. You need to make them the same by assigning the radius parameter to the radius field. To refer to the radius field, use this.radius.
this.radius = radius;
Because you did not do this in your code, the radius returned by getRadius is 0, which is the default value of an unassigned int.

Instance variable are assigned values by default if not initialized. In case of int it's 0 by default. So to assign the value to your instance variable radius you need to add this line in your constructor.
this.radius = radius
We are using this because your instance variable and local variable are having the same name.

Related

Why are my constructor arguments not passed?

Here is my class. In the main method at the bottom I pass two arguments in the constructor (int numTriangles, double radius) as (8,1). The variables declared at the top radius and numTriangles should assume those values as my constructor assigns them then runs a calculation. However I get divide by zero error when twoTheta is calculated as numTriangles is zero at this point. Why is this and how can I fix it? Thanks.
package Triangles;
public class Triangles {
double radius;
int numTriangles;
double twoTheta = 360/numTriangles;
double theta = twoTheta / 2;
double base;
double height;
double result;
double halfTriangleArea;
double triangleArea;
double area;
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
runCalculation();
}
// My methods
public double calculateBase() { // SOH
double thetaToRadians = Math.toRadians(theta);
double base = Math.sin(thetaToRadians) / radius;
return base;
}
public double calculateHeight() { // CAH
double thetaToRadians = Math.toRadians(theta);
double height = Math.cos(thetaToRadians) / radius;
return height;
}
public double checkPythag(double base, double height) {
double a = base;
double b = height;
double result = Math.sqrt(a*a + b*b);
return result;
}
public double calculateArea(double base, double height) {
double halfTriangleArea = (0.5) * base * height;
return halfTriangleArea;
}
public double runCalculation() {
base = calculateBase();
height = calculateHeight();
result = checkPythag(base, height);
halfTriangleArea = calculateArea(base, height);
triangleArea = 2 * halfTriangleArea;
// C = Pi * D = Pi * 2 * r
// A = Pi * r.^2
area = numTriangles * triangleArea;
// Substitute Pi for X
// area = X * r.^2
// if r is 1
// area = X
return area;
}
// Runnable
public static void main(String[] args) { // create an instance of class to run in main
Triangles triangles = new Triangles(8, 1);
System.out.println("radius: " + triangles.radius);
System.out.println("numTriangles: " + triangles.numTriangles);
System.out.println("twoTheta " + triangles.twoTheta);
System.out.println("theta " + triangles.theta);
System.out.println("base: " + triangles.base);
System.out.println("height: " + triangles.height);
System.out.println("checkPythag " + triangles.result + " | " + triangles.radius);
System.out.println("halfTriangleArea: " + triangles.halfTriangleArea);
System.out.println("triangleArea: " + triangles.triangleArea);
System.out.println("Approximation of Pi by triangles: " + triangles.area);
}
}
As multiple answers have pointed out, twoTheta (and theta as well) is initialized before constructor is called, hence the error.
I suggest you initialize twoTheta, and theta inside the constructor.
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
//Initialize twoTheta
this.twoTheta = 360/this.numTriangles;
this.theta = this.twoTheta/2;
runCalculation();
}
You call runCalculation() from the constructor - at this moment twoTheta has assigned it's default value (it's 0 for primitives and that default value is assigned even before constructor is called). There are two simple ways of solving your problem:
You should call runCalculation() from outside of the constructor to be sure that all fields are initialized to values other than default (to values that you specified)
OR
You could initialize twoTheta and thetain the constructor before calling runCalculation().
If you want to use first option - change your main method like this to see results that you expect:
public static void main(String[] args) {
Triangles triangles = new Triangles(8, 1);
triangles.runCalculation();
...
}
You should also delete call of runCalculation() from the body of the constructor.
If you choose second way of solving your problem, just initialize theta and twoTheta before runCalculation() in the constructor body:
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
this.twoTheta = 360/this.numTriangles;
this.theta = this.twoTheta/2;
runCalculation();
}
You might want to look here at official Java tutorial to see a list of default values assigned to primitive types and to read a bit more about it (by the way, objects are assigned to null by default).
Ths class attributes are initialized before the constructor is called.
So, the attribute numTriangles is first set to 0. After that double twoTheta = 360/numTriangles; is executed.
The constructor is called afterwards.
That's why you get your error.
Therefore, don't initialize the attributes twoTheta and theta directly but let the constructor handle it after having set the numTriangles and radius attributes.
Call runCalculation();
after
Triangles triangles = new Triangles(8, 1);
in your main method.
Let the constructor complete.
Because these definitions are executed at the creation of the class and not at the instantiation of the object. Furthermore, when you declare but don't assign radius or numTriangles, the default value 0 is used. The default value is 0 for any primitive type (double, int, float, ...) and null for any other type (String, Triangle, ...).
You should only declare them in the class and assign them in the constructor.
double radius;
int numTriangles;
double twoTheta;
public Triangle(double radius, int numTriangles) {
this.radius = radius;
this.numTriangles = numTriangles;
this.twoTheta = 360 / numTriangles;
}
You can change your code like this to avoid the error.
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
initialize();
runCalculation();
}
private void initialize()
{
twoTheta = 360/numTriangles;
theta = twoTheta / 2;
}

Program print keeps print 0.0 for Cylinder area, volume, range + inheritance java

I have tried this a couple of different ways. It is required I use the inheritance to extend these classes. Every time I run the program it just out puts 0.0 for volume and area. Radius displays correctly. Output at the bottom.
public class Base_HW04Q1
{
public double pi = 3.14, l, radius, height, area, volume;
public static class RoundShape extends Base_HW04Q1 {
public RoundShape(double radius) {
this.radius = radius;
}
public double calcArea () {
area = (radius * radius) * pi;
return area;
}
public String toString() {
return "A Round Shape of radius: " + radius + ", area " + area + ".";
}
}
public static class Cylinder extends Base_HW04Q1
{
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
public double calcArea() {
l = Math.sqrt((radius * radius) + (height * height));
area = 2 * pi * radius * height + 2 * pi * l;
return area;
}
public double calcVolume() {
volume = pi * (radius * radius) * height;
return volume;
}
public String toString() {
return "A Cylinder of radius: " + radius + ", area " + area + " and a volume of " + volume;
}
}
public static class Cone extends Base_HW04Q1 //TODO: This line is almost, but not quite, complete.
{
public Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}
public double calcArea() {
l = Math.sqrt((radius * radius) + (height * height));
area = (pi * radius * l) + (pi * radius * radius);
return area;
}
public double calcVolume() {
volume = 0.333 * pi * radius * radius * height;
return volume;
}
public String toString() {
return "A Cone of radius: " + radius + ", area " + area + " and a volume of " + volume;
}
}
public static void main(String[] args)
{
//object creation
Cylinder Cylinder1 = new Cylinder(30, 10);
Cone Cone1 = new Cone(10, 20);
RoundShape RoundShape1 = new RoundShape(50);
//print for objects
System.out.println(Cylinder1);
System.out.println(RoundShape1);
System.out.println(Cone1);
}
}
Output:
A Cylinder of radius: 30.0, area 0.0 and a volume of 0.0 A Round Shape
of radius: 50.0, area 0.0. A Cone of radius: 10.0, area 0.0 and a
volume of 0.0
Your toString() never calls the methods that do the calculations and instead prints the default 0.0 field values. You will run this risk if toString() is ever called before the calcXxxx() methods are called, i.e., before the calculated fields have been given a decent value. The best solution is to prevent this problem from happening in the first place by entirely getting rid of fields for calculated values, for instance area and volume. Instead within toString(), call the methods to get these values.
e.g.,
public double pi = 3.14, l, radius, height; // , area, volume;
public static class RoundShape extends Base_HW04Q1 {
public RoundShape(double radius) {
this.radius = radius;
}
public double calcArea () {
return (radius * radius) * pi;
// return area;
}
public String toString() {
return "A Round Shape of radius: " + radius + ", area " + calcArea() + ".";
}
}
It's because you only instantiate the object and entered to constructor but not in the other method.
Cylinder Cylinder1 = new Cylinder(30, 10);
Cone Cone1 = new Cone(10, 20);
RoundShape RoundShape1 = new RoundShape(50);
no one called in these methods
public double calcArea() {
l = Math.sqrt((radius * radius) + (height * height));
area = (pi * radius * l) + (pi * radius * radius);
return area;
}
public double calcVolume() {
volume = 0.333 * pi * radius * radius * height;
return volume;
}
public String toString() {
return "A Cone of radius: " + radius + ", area " + area + " and a volume of " + volume;
}
and the rest methods. Call them from constructor or from main if you want to calculate through method like:
public static void main(String[] args)
{
//object creation
Cylinder Cylinder1 = new Cylinder(30, 10);
Cone Cone1 = new Cone(10, 20);
RoundShape RoundShape1 = new RoundShape(50);
double roundArea = RoundShape1.calcArea();//then use this
string roundMessage = RoundShape1.toString();//and this whatever you want.
//do it in others too
//print for objects
System.out.println(Cylinder1);
System.out.println(RoundShape1);
System.out.println(Cone1);
}

Math from class isn't carrying in to object

I have to make a program that has the Circle class which calculates the area and circumference of a circle by accepting a parameter for r from a new circle object in main. I fed it the radius value of 14. This is what it should output:
***** Circle *****
radius 14.0
area 615.75164
circumference 87.96452
But instead I'm getting this
***** Circle *****
radius 14.0
area 0.0
circumference 0.0
Why is this happening and how can I fix it? I was given the overall shell of the code to make work in java and I have to keep it for the most part how it was presented to me, so while I appreciate the intention of giving recommendations on better ways to structure things and make this program in general, the teacher wants me to do it this way. The only thing I'm not sure of is what to do with setRadius(), and whether or not I should have declared r at the top of the class.
package shapedemo;
class Circle {
private double radius;
private double circumference;
private double area;
private double r;
// constructors
public Circle(){
radius = 1;
}
public Circle(double r) {
radius = r;
}
// setters and getters
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
// other methods
public double calcArea() {
area = Math.PI * r * r;
return area;
}
public double calcCircumference(){
circumference = Math.PI * 2 * r;
return circumference;
}
// display method
public void display() {
/*blank line
***** Circle *****
radius nnnn.nn
area nnnn.nn
circumference nnnn.nn
blank line
*/
System.out.println("\n***** Circle *****\nradius " + radius + "\narea " + area + "\ncircumference " + circumference + "\n");
}
}
public class ShapeDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Circle circle1 = new Circle(14);
circle1.display();
}
}
Your area and circumference variables are only being set if you call the appropriate calculation methods (calcArea and calcCircumference). You're not calling them, so they have the default values of 0.
You could fix this in your main method:
public static void main(String[] args) {
Circle circle = new Circle(14);
circle.calcArea();
circle.calcCircumference();
circle.display();
}
... although you'd also have to fix your methods to use radius instead of r, as you're never setting r.
Personally I think it would be better to either move the logic into your constructor or calculate it on demand with methods rather than having fields at all for them.
First approach, in the constructor:
final class Circle {
private final double radius;
private final double circumference;
private final double area;
public Circle() {
this(1); // Delegate to other constructor
}
public Circle(double r) {
radius = r;
area = Math.PI * radius * radius;
circumference = Math.PI * 2 * radius;
}
public void display() {
System.out.println(
"\n***** Circle *****" +
"\nradius " + radius +
"\narea " + area +
"\ncircumference " + circumference + "\n");
}
}
Second approach, making methods compute the values:
final class Circle {
private final double radius;
public Circle() {
this(1); // Delegate to other constructor
}
public Circle(double r) {
radius = r;
}
public double getRadius() {
return radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getCircumference() {
return Math.PI * 2 * radius;
}
public void display() {
System.out.println(
"\n***** Circle *****" +
"\nradius " + radius +
"\narea " + getArea() +
"\ncircumference " + getCircumference() + "\n");
}
}
In both cases, I've made this an immutable type - while you can keep it mutable, in the first case that would mean recomputing the area and circumference. In that case you'd probably want your constructor to just call setRadius() and make that method do all the computations.
For example:
final class Circle {
private double radius;
private double circumference;
private double area;
public Circle() {
this(1); // Delegate to other constructor
}
public Circle(double r) {
setRadius(r);
}
public void setRadius(double r) {
radius = r;
area = Math.PI * radius * radius;
circumference = Math.PI * 2 * radius;
}
public double getRadius() {
return radius;
}
public double getArea() {
return area;
}
public double getCircumference() {
return circumference;
}
public void display() {
System.out.println(
"\n***** Circle *****" +
"\nradius " + radius +
"\narea " + area +
"\ncircumference " + circumference + "\n");
}
}
You never call to calcArea() and calcCircumference(), so circumference and area have the intial 0 value.
Circle circle1 = new Circle(14);
circle1.calcArea();
circle1.calcCircumference();
circle1.display();
Or change your constructor to
public Circle(double r) {
radius = r;
calcArea();
alcCircumference();
}
You're not calling the calcArea and calcCircumference so they retain the default value 0.0d
this should be your public static void main()
public static void main(String[] args) {
Circle circle1 = new Circle(14);
circle1.calcArea();
circle1.calcCircumference();
circle1.display();
}
Also, change your return type of calcArea() and calcCircumference() to void

Encapsulation with Java

I'm trying to implement encapsulation in a program as part of some coursework however I've run into an error which I just can't seem to be able to fix with my limited knowledge which isn't helped by my Teacher/Lecturer who is very good at what he does however doesn't do very well when it actually comes to communicating the information, because of this could someone help me fix the error which is presented from the following program and explain to me why it's not working as intended.
class TwoDShapeEncap{
double width, height;
//Width
void setWidth(double w){
width = w;
}
double getWidth(){
return width;
}
//Height
void setHeight(double h){
height = h;
}
double getHeight(){
return height;
}
}
class Triangle extends TwoDShapeEncap{
String type;
private double sideA, sideB, sideC, adjacent, opposite;
//Side A
void setsideA(double a){
sideA = a;
}
double getsideA(){
return sideA;
}
//Side B
void setsideB(double b){
sideB = b;
}
double getsideB(){
return sideB;
}
//Side C
void setsideC(double c){
sideC = c;
}
double getsideC(){
return sideC;
}
//Adjacent
void setadjacent(double a){
adjacent = a;
}
double getadjacent(){
return adjacent;
}
//Opposite
void setopposite(double o){
width = o;
}
double getopposite(){
return opposite;
}
double getPerimeter(){
if(getsideB() == 0.0 && getsideC() == 0.0){
type = "equilateral";
return getsideA() * 3;
}
else if (getsideC() == 0.0){
type = "isosceles";
return getsideA() + getsideB() * 2;
}
else{
type = "scalene";
return getsideA() + getsideB() + getsideC();
}
}
//*******************************************************************************************
//* Paste the perimeter() and hypotenuse() methods from your previous class into this class *
//*******************************************************************************************
//***************************************
//* add an area method()into this class *
//***************************************
double area(double a, double b){
getWidth();
getHeight();
return (getWidth() * getHeight()/2);
}
}
class Rectangle extends TwoDShapeEncap{
boolean issquare;
private double height, width;
//Height
void setHeight(double h){
height = h;
}
double getHeight(){
return height;
}
//Width
void setWidth(double w){
width = w;
}
double getWidth(){
return width;
}
double perimeter(double h, double w){
getHeight();
getWidth();
return getHeight() * 2 + getWidth() * 2;
}
double area(double a, double b){
//getWidth();
//getHeight();
return (getWidth() * getHeight()/2);
}
boolean testSquare(double h, double w){
//getHeight();
//getWidth();
if (getHeight() == getWidth())
issquare = true;
else issquare = false;
return issquare;
}
//*********************************************
//* add area and perimeter methods this class *
//*********************************************
//*************************************************************************
//* add a testSquare method to test if a particular rectangle is a square *
//*************************************************************************
}
//Add a circle class which includes area and circumference methods
class Circle extends TwoDShapeEncap{
double radius, diameter;
double area (double r){
radius = r;
return Math.PI * (radius * radius);
}
double perimeter (double r){
radius = r;
return 2 * (Math.PI * radius);
}
}
class TwoDShapeEncapDemoNew {
public static void main(String args[]) {
//Triangle
Triangle t = new Triangle();
t.setsideA(5.7);
System.out.println("The perimeter is " + t.getPerimeter());
System.out.println("If sideA is " + t.getsideA() );
System.out.println("The type is " + t.type);
System.out.println();
t.setsideB(7.3);
System.out.println("The perimeter is " + t.getPerimeter());
System.out.println("If sideA is " + t.getsideA() );
System.out.println("If sideB is " + t.getsideB() );
System.out.println("The type is " + t.type);
System.out.println();
t.setsideC(2.7);
System.out.println("The perimeter is " + t.getPerimeter());
System.out.println("If sideA is " + t.getsideA());
System.out.println("If sideB is " + t.getsideB());
System.out.println("If sideC is " + t.getsideC());
System.out.println("The type is " + t.type);
System.out.println();
//Rectangle
Rectangle r = new Rectangle();
r.setHeight(7.8);
r.setWidth(4.2);
System.out.println("The perimeter is " + r.perimeter());
System.out.println("The");
}
}
Error message:
Main.java:186: error: method perimeter in class Rectangle cannot be applied to given types; System.out.println("The perimeter is " + r.perimeter()); ^ required: double,double found: no arguments reason: actual and formal argument lists differ in length 1 error –
When you call:
System.out.println("The perimeter is " + r.perimeter());
in r.perimeter you must pass two parameters (as your signature wants)
Your method in Rectangle class:
double perimeter(double h, double w){
getHeight();
getWidth();
return getHeight() * 2 + getWidth() * 2;
}
So fix:
System.out.println("The perimeter is " + r.perimeter(r.getHeight(), r.getWidth()));
You also can fix your method perimeter without parameters because in the body you use getHeigth() and getWidth() properties
So you can write:
double perimeter(){
return getHeight() * 2 + getWidth() * 2;
}
The method perimeter in the class Rectangle expects two parameters, and you're not passing any. You could either call it like this:
r.perimeter(7.8,4.2);
Or redefine the method so it looks like this:
double perimeter(){
return getHeight() * 2 + getWidth() * 2;
}
Thats because you are defining the perimeter function like this:
double perimeter(double h, double w){
getHeight();
getWidth();
return getHeight() * 2 + getWidth() * 2;
}
and calling System.out.println("The perimeter is " + r.perimeter()); with no parameters.
Since you are not really using double h and double w for nothing, you just have to remove them from the method definition
double perimeter(){
return getHeight() * 2 + getWidth() * 2;
}
Since everybody is just facing the problem with the parameters I will face this problem: Getters are used to get the values of private fields if you're "outside" your class! If you're in a method in your class you don't have to use the getters, you can just use the variables themselfs:
Example:
public class SomeClass {
private int a;
public void setA(int anotherA) {
a = anotherA;
}
public int getA() {
return a;
}
public int getSquareOfA() {
// You don't use getA() to get the value now
// but you use a itself!
return a*a; // instead of 'return getA() * getA();'
}
}
You do have that problem at several points in your code!
According to your problem:
Your problem was that you're calling a method which has 2 parameters without any input parameters!
You can either remove the parameters of the method (which will be the logically right thing to do in your case), OR you pass some parameters.
In your specific case that means, change your perimiter() method as follows:
double perimiter() {
return (height + width) * 2;
// or if you want to impress your teacher ;) :
// return (height + width) << 1
}
Also you should change that methodname to getPerimiter() to keep up with your own naming conventions!
Modify your signature to remove the arguments.
class Rectangle extends TwoDShapeEncap{
///...
double perimeter(double h, double w){
getHeight();
getWidth();
return getHeight() * 2 + getWidth() * 2;
}
should be
class Rectangle extends TwoDShapeEncap{
///...
double perimeter(){
//Notice that you don't need to pass in these arguments
//as this function gets these arguments by itself.
return getHeight() * 2 + getWidth() * 2;
}

Java Program Circumference and Area

I got the assignment to write a Java program that gives the circumference and area of a circle of radius 1 through 50. This is what I've got:
public class Circles {
public static void main(String[] args) {
}
{
for (int i = 1; i <=50; i=i+1)
area = PI * (radius * radius);
System.out.println("The area is " + area);
double circumference= PI * 2*radius;
System.out.println( "The circumference "+circumference) ;
}
}
It says that radius, pi, and area cannot be resolved to a variable.
Because you never declared them as variables (nor, in the cases of PI and radius, even give them values). Notice that it did not complain about circumference, which you did declare.
You have to declare your variables - at the moment you're only declaring two of them, namely i and circumference. Also, Java has a PI constant which is found in the Math class, so you'll need Math.PI:
public static void main(String[] args) {
for (int i = 1; i <=50; i=i+1) {
double radius = i;
double area = Math.PI * (radius * radius);
System.out.println("The area is " + area);
double circumference = Math.PI * 2*radius;
System.out.println( "The circumference "+circumference) ;
}
}
public class Circles {
public static void main(String[] args) {
double PI = Math.PI;
for (int radius = 1; radius <=50; i=i+1) {
double area = PI * (radius * radius);
System.out.println("The area is " + area);
double circumference= PI * 2*radius;
System.out.println( "The circumference "+circumference) ;
}
}

Categories

Resources