質問

Here is my code: What I am looking to do is in the output I have color display for circle one but not in circle 2 and I am not sure why. Can someone help me with this?

Here is my first set of code:

 public class Circle
 {
 private double radius;
 private String color;

 public Circle()
 {
   radius = 1.0;
   color = "red";
}

public Circle(double newRadius)
{ 
    radius = newRadius;
}

public double getRadius()
{
    return radius;
}

public double getArea()
{ double ar = Math.PI * radius * radius;

    // round the area up to two decimals
    ar = Math.round(ar * 100.0) / 100.0;

    return ar;
} 
public Circle (String newColor){
   color = newColor;
}
public String getColor(){

   return color;
 }
}

Here is the second part with the main method:

 public class TestCircle
  {
 public static void main(String[] args)
 {
   Circle cir1 = new Circle();

   System.out.println("Details of circle 1:");
   System.out.println("Radius: " + cir1.getRadius());
   System.out.println("Area: " + cir1.getArea());
   System.out.println("Color: " + cir1.getColor());

   Circle cir2 = new Circle(5);
   System.out.println("******************************");
   System.out.println("Details of circle 2:");
   System.out.println("Radius: " + cir2.getRadius());
   System.out.println("Area: " + cir2.getArea());
   System.out.println("Color: " + cir2.getColor());

}
}

Here is the output:

Details of circle 1:

Radius: 1.0

Area: 3.14

Color: red


Details of circle 2:

Radius: 5.0

Area: 78.54

Color: null

役に立ちましたか?

解決 2

This happens because you only set the colour in one of your constructors. So when you create an object such as cir2, using the second constructor, the colour doesn't get set.

To fix this, add a line to the second constructor to set the colour. Maybe it could be like this.

public Circle(double newRadius)
{ 
    radius = newRadius;
    color = "blue";
}

他のヒント

Your second circle uses the constructor

public Circle(double newRadius)
{ 
    radius = newRadius;
}

which doesn't assign a color.

I'm not sure if you intended for your newColor method to be a constructor. You probably want a setter for color:

public void setColor(String newColor) {
    this.color = newColor
}

With this in place you could do someting along the lines of:

Circle cir2 = new Circle(5);
cir2.setColor("red")
System.out.println("Color: " + cir2.getColor());

Or, if you want it to work like cir1, add color assignment to the double constructor as well.

You circle 2 uses below constructor and it has no reference to setting a colour....where as default constructor does.

public Circle(double newRadius)
{ 
    radius = newRadius;
}

In my opinion, you may add another parameter to this constructor for taking a value for colour as per user's preference.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top