why is my setter and getter methods not working? - java

I have been looking at my source code and can't figure out what is wrong with it.
The problem I think is with the Circle class. When I call the mutators and accessors from
the DriverCircle class it's giving me the wrong output. For getDiameter it's just printing out 0s.
public class Circle{
private double radius;
private double pi;
private double diameter;
private double circumference;
private double area;
public Circle(){
pi = Math.PI;
radius = 0;
}
public Circle(double radius){
this.radius = radius;
}
public void setDiameter(){
diameter = (2 * radius);
}
public double getDiameter(){
//diameter = 2 * radius;
return diameter;
}
public void setCircumference(){
circumference = (2 * pi * radius);
}
public double getCircumference(){
//circumference = 2 * pi * radius;
return circumference;
}
public double getArea(){
//area = pi * Math.pow(radius, 2);
return area;
}
public void setArea(){
area = (pi * Math.pow(radius, 2));
}
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
public String toString(){
return "The radius is " + radius;
}
}
(The tester)...
import java.util.Scanner;
public class CircleDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the radius: ");
Circle[] circles = new Circle[10];
Circle objectCircle = new Circle();
objectCircle.setRadius(input.nextDouble());
circles[1] = new Circle();
circles[2] = new Circle(2.0);
circles[3] = new Circle(3.5);
circles[4] = new Circle(5.0);
circles[5] = new Circle(0.0);
circles[6] = new Circle(15);
circles[7] = new Circle(25);
circles[8] = new Circle(-7);
circles[9] = new Circle(-10.0);
System.out.println("Initial call to toString():");
for (Circle c : circles)
{System.out.println("\t" + c);}
System.out.println("Call to getRadius (should be same as above):");
for (Circle r : circles)
{if (r != null)
{System.out.println("\t" + r.getRadius());}}
System.out.println("Call to getDiameter (should be twice the value shown above):");
for (Circle d : circles)
{if (d != null)
{System.out.println("\t" + d.getDiameter());}}
System.out.println("Calls to getCircumference:");
System.out.println("\tShould be 2 * PI: " + circles[1].getCircumference());
System.out.println("\tShould be 0.0: " + circles[5].getCircumference());
System.out.println("\nCall to getArea:");
System.out.println("\tShould be PI: " + circles[1].getArea());
System.out.println("\tShould be 0.0: " + circles[5].getArea());
System.out.println("Testing out the setRadius method:");
for (int i = 0; i < circles.length / 2; i++)
{if (circles[i] != null)
{circles[i].setRadius(i);}}
System.out.println("Call to toString after setting the first half of the objects:");
for (Circle c : circles)
{System.out.println("\t" + c);}
}
}

Your setter methods should have parameters and use the parameters to set fields. Else they are not in fact setter methods. Your current setter methods should all be discarded, except perhaps setRadius(...), and most of the calculations be done in the respective getter methods.
i.e., not
public void setCircumference(){
circumference = (2 * pi * radius);
}
public double getCircumference(){
//circumference = 2 * pi * radius;
return circumference;
}
but rather
public double getCircumference(){
return 2 * Math.PI * radius;
}

pi isn't initialized when you provide a value in constructor. Further, storing pi as an instance member is a bit weird. Just user Math.PI in your calculations.

You never call setDiameter(). Your constructor sets the value of the radius, but it doesn't do anything about setting the diameter variable!
You may just want to rewrite getDiameter():
public double getDiameter() {
return 2.0 * radius;
}

You constructed a Circle object, which sets the radius, but you never set the diameter. Should probably call setDiameter() from the constructor.
Better yet, delete the setDiameter() method as it's completely unnecessary. Simply make getDiameter() return 2*radius.

I see two problems.
First, and foremost, you don't set the value of pi if you use the double constructor. You should also use the no-args constructor as well as set the value of your radius:
public Circle(double radius){
this(); // calls the no-args constructor
this.radius = radius;
}
Second, there's no explicit call to setDiameter(). Funnily enough, that method is a misnomer - it should be calculated whenever the radius is nonzero. setArea is the same way - you're not passing anything in to that method call. Here's what I would recommend:
Rename setDiameter to calculateDiameter to make its intention clear. The reason for the rename is to have this class follow JavaBean conventions with respect to set and get.
In public Circle(double radius), call calculateDiameter() immediately afterwards.
Whenever setRadius() is called, either immediately follow it with a call to calculateDiameter or violate JavaBean conventions and call it immediately after the value is set.
It's strongly encouraged to do the same thing for getArea, but I'll leave that portion as an exercise to the reader.
In code, a brief example:
public Circle(double radius){
this(); // calls the no-args constructor
this.radius = radius;
calculateDiameter();
}
public void setRadius(double r) {
radius = r;
calculateDiameter();
}

Just setting the radius does not update every function that uses radius; you have to call those functions explicitly or else they remain at Java's default of 0.
I would also do any error checking at the Circle(radius) method; that way no negative numbers make it into the set of radii.

Related

Please explain this unexpected output of this JAVA program

In the following program I was jus t trying to create a simple class for as Circle circ and then tried to inherit a Cylinder from it cylind. I defined several methods to find the perimeter, area and volume of these geometrical objects but I am constantly getting wrong answer. I had spent several painstaking our hour to find the error but I am unable to find it. I am a beginner so I think there might be something I may have missed. Please help.
package com.company;
class circ {
int radius;
public circ(int radius) {
this.radius = radius;
}
}
class cylind extends circ{
int height;
double area = (2*Math.PI * radius * ( radius + height ));
double volume = (Math.PI * radius *radius * height );
public cylind(int radius, int height) {
super(radius);
this.height = height;
}
public void area() {
System.out.println("Total Surface Area = " + this.area);
}
public void volume(){
System.out.println("Volume = " + this.volume);
}
}
class Trial_and_error_2 {
public static void main(String[] args) {
cylind b =new cylind(10,45);
System.out.println(b.radius);
System.out.println(b.height);
System.out.println(2*Math.PI * b.radius * ( b.radius + b.height ));
System.out.println(Math.PI * b.radius *b.radius * b.height );
b.area();
b.volume();
}
}
Output: I have used ----> to explain the output and the problem.
10 ---> Radius
45 ---> height
3455.7519189487725 ---> Surface area calculated in the main block
14137.16694115407 ---> Volume calculated in the main block
Total Surface Area = 628.3185307179587 ---> Wrong values of Surface area printed by the method of class THIS IS THE PROBLEM.
Volume = 0.0 ---> Wrong values of volume printed by the method of class THIS IS THE PROBLEM.
Instance variables "area" and "volume" are initialized BEFORE the constructor is called. That's why you get volume = 0, because height is 0 when that happens.
Your field calculations will be executed before the constructor.
Solution:
Just move calculations to constructor:
public Cylinder(int radius, int height) {
super(radius);
this.height = height;
area = 2*Math.PI * radius * (radius + height);
volume = Math.PI * radius *radius * height;
}
Also, I will recommend using full class names with a first capital.

Problems with setters and getters in java program dealing with circles

I have been assigned the following task for an introductory java course:
You should write a class that represents a circle object and includes the following:
Private class variables that store the radius and centre coordinates of the object.
Constructors to create circle objects with nothing supplied, with just a radius value supplied and with a radius and centre coordinates supplied.
Public instance methods that allow the radius and centre coordinates to be set and retrieved (often known as set/get methods).
Public instance methods that return the circumference and area of the circle.
A public class method that tests if two circle objects overlap or not
Here is my code:
import java.lang.Math;
public class Circle {
private double xCentre, yCentre, Radius;
// constructors
public Circle() {
xCentre = 0.0;
yCentre = 0.0;
Radius = 1.0;
}
public Circle(double R) {
xCentre = 0.0;
yCentre = 0.0;
Radius = R;
}
public Circle(double x, double y, double R) {
xCentre = x;
yCentre = y;
Radius = R;
}
//getters
public double getX() {
return xCentre;
}
public double getY() {
return yCentre;
}
public double getRadius() {
return Radius;
}
//setters
public void setX(double NewX) {
xCentre = NewX;
}
public void setY(double NewY) {
yCentre = NewY;
}
public void setRadius(double NewR) {
Radius = NewR;
}
//calculate circumference and area
public double Circumference() {
return 2*Math.PI*Radius;
}
public double Area() {
return Math.PI*Radius*Radius;
}
//determine overlap
public static double Overlap(Circle c1, Circle c2) {
double xDelta = c1.getX() - c2.getX();
double yDelta = c1.getY() - c2.getY();
double separation = Math.sqrt(xDelta*xDelta + yDelta*yDelta);
double radii = c1.getRadius() + c2.getRadius();
return separation - radii;
}
}
}
and
import java.io.Console;
public class cp6 {
public static void main(String args[]){
//Set up the Console
Console myConsole = System.console();
//Declare cirlce
Circle first = new Circle(2.0,4.0,6.0);
myConsole.printf("Circumference of first circle is ", first.Circumference(), "\n");
myConsole.printf("Area of first circle is ", first.Circumference(), "/n");
first.setRadius(2);
first.setX(2);
first.setY(2);
myConsole.printf("New X of first circle is ", first.getX(), "/n");
myConsole.printf("New Y of first circle is ", first.getY(), "/n");
myConsole.printf("New Radius of first circle is ", first.getRadius(), "/n");
Circle second = new Circle(-1.0,3.0,5.0);
Circle third = new Circle(1,1,1);
if (Circle.Overlap(second, third) <= 0) {
myConsole.printf("Second and third circles overlap");
}
else {
myConsole.printf("Second and third circles do not overlap");
}
myConsole.printf("New Y of first circle is ", first.getY());
Calculate and print out distance between them using the class method
myConsole.printf("Distance between first and second is : %.5g\n", Circle.Overlap(first, second));
}
}
The second program just has to demonstrate each aspect addressed in the brief I pasted at the top and I've only a rough idea of how to do this so if what I'm doing seems stupid to any of you please offer suggestions of what else I can do.
Your problem is that you're using the Console.printf() method incorrectly.
The first parameter to this method should be a format, and it has to have placeholders inside it for the other parameters. Read up on it in The Java Platform documentation. In fact, you should familiarize yourself with the Java platform documentation. You need to use it often to make sure you're calling methods correctly or what methods are available in a given class.
So, your printout lines should actually have been:
myConsole.printf("Circumference of first circle is %.2f%n", first.Circumference());
myConsole.printf("Area of first circle is %.2f%n", first.Area());
...etc.
The format %.2f means "The corresponding parameter is a floating-point number. Display it with a precision of 2 digits after the decimal point". The %n replaces your "\n" - the whole "template" of the print should be just in the format string. And in this type of format, one should use %n instead of \n.
I'm not sure why you opted for using the system console rather than the usual System.out.println(). If you choose to go with System.out, there is also a printf() method there that works exactly as Console.printf() - the first parameter is a format, the others are embedded in it.
One last comment: there are conventions when writing Java code:
Indent your code properly
Class names' first letter is always uppercase.
Non-constant fields and local variable names' first letter is always lowercase.
Method names also start with a lowercase letter.

Variables from the main class to be assigned to variables in the subclasses - beginner

I have this code which will find the area of different shapes depending on the inputted shape of the user. The problem is how can I get the inputted measurements(e.g. length, width) from the main class to the Circle, triangle, rectangle and square classes? here's my code.
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
class Circle{
double radius;
void CircleMeasurement(){
radius = r;
}
double getCircleArea(){
return(Math.PI*Math.pow(radius,2));
}
}
class Triangle{
int base, height;
void TriangleMeasurement(){
base = b;
height = h;
}
int getTriangleArea(){
return((base*height)/2);
}
}
class Rectangle{
int length, width;
void RectangleMeasurement(){
length = l;
width = w;
}
int getRectangleArea(){
return(length*width);
}
}
class Square{
int sides;
void SquareMeasurement(){
sides = s;
}
int getSquareArea(){
return( sides * sides);
}
}
class Shapes{
public static void main(String[] args){
String key;
double r;
int b, h, l, w, s;
System.out.println("Welcome!");
System.out.println("Choose your option:");
System.out.println("1 - Circle, 2 - Triangle, 3 - Rectangle, 4 - Square");
Scanner in = new Scanner(System.in);
key = in.nextLine();
if (key=="1" || key =="circle"){
System.out.println("Area for Circle");
System.out.println("Enter radius:");
Scanner.in = new Scanner(System.in);
r = in.nextInt;
Circle circle1 = new Circle();
System.out.println("The area is equal to" + circle1.getCircleArea());
}
else if (key == "2"){
System.out.println("Area for Triangle");
System.out.println("Enter base:");
Scanner.in = new Scanner(System.in);
b = in.nextInt;
System.out.println("Enter height:");
h = in.nextInt;
Triangle triangle1 = new Triangle();
System.out.println("The area is equal to" + triangle1.getTriangleArea());
}
else if (key == "3"){
System.out.println("Area for Rectangle");
System.out.println("Enter length:");
Scanner.in = new Scanner(System.in);
l = in.nextInt;
System.out.println("Enter width:");
w = in.nextInt;
Rectangle rectangle1 = new Rectangle();
System.out.println("The area is equal to" + rectangle1.getRectangleArea());
}
else if (key == "4"){
System.out.println("Area for Square");
System.out.println("Enter side:");
Scanner.in = new Scanner(System.in);
s = in.nextInt;
Square square1 = new Square();
System.out.println("The area is equal to" + square1.getSquareArea());
}
}
}
You can set the appropriate variables at the time of Object creation using constructor.
Circle(int r){
radius = r;
}
Rectangle(int l, int b){
length = l;
breadth = b;
}
Circle c = new Circle(9); //creates a new Circle with radius 9
Rectangle r = new Rectangle(2,3) //Creates a new Rectangle with length as 2, breadth as 3
That said, you can also use setter methods.
Also, using == to compare Strings is frowned upon and often will give you wrong results. Use
.equals() instead.
"Circle".equals(input);
Two things to mention here:
Pass the values taken from scanner to classes as argument to method or constructor. So it can be used by method for furthur calculations. Also using inheritance here will be a good option.
Never use == for string comparision. It will not work, use .equals instead.
One of the problem in your code is that you are comparing string using ==. Strings should be compared using equals method.
change such statements
if (key=="1" || key =="circle"){
to
if (key.equals("1") || key.equals("circle")){
The other problem is that you have not defined constructors with proper arguemnts in your classes such as Circle, Triangle etc. As you are not setting the proper attributes so calling the methods will not provide you the correct results.
For example you need to have constructor in Circle class,to initialize the radius param:
public Circle(int r) {
radius = r;
}
And creating the object of Circle like this, followed by call to getCircleArea should give u the desired result:
Circle circle1 = new Circle(r);
System.out.println("The area is equal to" + circle1.getCircleArea());
You can set values of variables in several ways. First way it's constructor, see rocketboy answer. Second one it's mark your variables as private and use mutator methods. It's recomended way/ See example below:
class Circle{
private double radius;
Circle(double radius){
this.radius = radius;
}
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
Firs you should create getters and setters.Then
class Circle{
double radius;
public double getRadius(){
return radius;
}
public void setRadius(double r){
radius=r;
}
void CircleMeasurement(){
radius = r;
}
....
r = in.nextInt;
Circle circle1 = new Circle();
circle1.setRadious(r);

Java error - "invalid method declaration; return type required"

We are learning how to use multiple classes in Java now, and there is a project asking about creating a class Circle which will contain a radius and a diameter, then reference it from a main class to find the diameter. This code continues to receive an error (mentioned in the title)
public class Circle
{
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
Thanks for any help, -AJ
Update 1:
Okay, but I shouldn't have to declare the third line public CircleR(double r) as a double, right? In the book I am learning from, the example doesn't do that.
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
//This is a method. It performs some action (in this case it calculates the
//area of the circle and returns it.
public double area( ) //area method
{
double a = Math.PI * radius * radius;
return a;
}
public double circumference( ) //circumference method
{
double c = 2 * Math.PI * radius;
return c;
}
public double radius; //This is a State Variable…also called Instance
//Field and Data Member. It is available to code
// in ALL the methods in this class.
}
As you can see, the code public Circle(double r).... how is that different from what I did in mine with public CircleR(double r)? For whatever reason, no error is given in the code from the book, however mine says there is an error there.
As you can see, the code public Circle(double r).... how is that
different from what I did in mine with public CircleR(double r)? For
whatever reason, no error is given in the code from the book, however
mine says there is an error there.
When defining constructors of a class, they should have the same name as its class.
Thus the following code
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
....
}
is correct while your code
public class Circle
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from
public CircleR(double r)
to
public Circle(double r)
or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.
So your new class should be
public class CircleR
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public double diameter()
{
double d = radius * 2;
return d;
}
}
I also added the return type double in your method as pointed out by Froyo and John B.
Refer to this article about constructors.
HTH.
Every method (other than a constructor) must have a return type.
public double diameter(){...
You forgot to declare double as a return type
public double diameter()
{
double d = radius * 2;
return d;
}
I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.

A really simple Java question

I'm trying to call angles from from the angle method down below in the Rotate90 method but I'm not sure of the syntax. What is the correct syntax?
import java.lang.Math;
public class CartesianPoint implements Point
{
private double xCoord;
private double yCoord;
public CartesianPoint (double xCoordinate,double yCoordinate)
{
xCoord = xCoordinate;
yCoord = yCoordinate;
}
public double xCoordinate ()
{
return xCoord;
}
public double yCoordinate ()
{
return yCoord;
}
public double angle ()
{
double angles;
angles = Math.cos( xCoord / Math.sqrt( xCoord*xCoord + yCoord*yCoord));
return angles;
}
public double radius ()
{
double radius;
radius = (yCoord*yCoord + xCoord*xCoord); //?
return radius;
}
public Point rotate90()
{
double rotated;
rotated = angles.angle + 90.0; //██████████ Error here ██████████
return rotated;
}
public double distanceFrom(Point other)
{
return 0;
}
}
I think you mean
rotated = angle() + 90.0;
Except I think you'll find that Math.cos uses radians not degrees, so you're not going to get the result you think you are. And shouldn't that be arc cos, not cosine? Something like this might be more what you're looking for:
public double angle()
{
return Math.atan2(ycoord, xcoord) * 180 / Math.PI;
}
If you want rotate90 to return a new Point that is 90 degrees from the current point, then change it to the following:
public Point rotate90()
{
return new CartesianPoint(-yCoord, xCoord);
}
Method invocations in Java always have trailing parentheses even when they don't have any arguments:
rotated = angle() + 90.0;
Method call requires parenthesis even if there are no parameters needed. This is different from other languages, e.g.groovy.
To answer your question directly: If you want to be able to access the variable "angles" from outside the "angle" function, you must make it a class variable. That is, declare it outside of any function, like you have declared xCoord and yCoord. Then refer to it by its simple name without any reference to the function that created it.
Note that if rotate90 tries to reference angle before angles() is called, angle will contain zero (or whatever default value you set) and is unlikely to be useful.
It's not clear to me exactly what you're trying to accomplish. I think that your intent is that the angles function would take the arc cosine, not the cosine.

Categories

Resources