Encapsulation with Java - 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;
}

Related

Assist me in finding the error: invalid method declaration; return type required

This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.
I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.
public class Exercise09_01 {
private double width = 1;
private double height = 1;
public Rectangle() {
}
public Rectangle(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Rectangle rectangle1 = new Rectangle(4, 40);
System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
rectangle1.getArea());
System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
rectangle1.getPerimeter());
Rectangle rectangle2 = new Rectangle(3.5, 35.9);
System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
rectangle2.getArea());
System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
rectangle2.getPerimeter());
}
}
This is my last homework for this class I just want this over with any help is appreciated.
The constructor name should have the same name as the class name
public class Exercise09_01 {
private double width = 1;
private double height = 1;
public Exercise09_01() {
}
public Exercise09_01(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}
}
public Rectangle() {
}
This is a method as far as Java is concerned. And all methods have to have a return type.
public Rectangle(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}
The same here.
You don't need the 1st one really unless you really need to be able to make one without those values set.
You can just rename them, but you probably just want to rename the class Rectangle
Whats wrong in your code is your class name and constructor names are different.
You have two options, one is to rename the constructor to Exercise01_01 or meke the return type of the Rectangle as void.
public class Exercise01_01 {
private double width = 1;
private double height = 1;
public Exercise01_01() {
}
public Exercise01_01(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Exercise01_01 rectangle1 = new Exercise01_01(4, 40);
System.out.println("The area of a 4.0 x 40.0 Rectangle is " + rectangle1.getArea());
System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " + rectangle1.getPerimeter());
Exercise01_01 rectangle2 = new Exercise01_01(3.5, 35.9);
System.out.println("The area of a 3.5 x 35.9 Rectangle is " + rectangle2.getArea());
System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " + rectangle2.getPerimeter());
}
}
public class Exercise09_01 {
private double width = 1;
private double height = 1;
public Exercise09_01() {
}
public Exercise09_01(double newWidth, double newHeight) {
width = newWidth;
height = newHeight;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public static void main(String[] args) {
Exercise09_01 rectangle1 = new Exercise09_01(4, 40);
System.out.println("The area of a 4.0 x 40.0 Rectangle is " + rectangle1.getArea());
System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
rectangle1.getPerimeter());
Exercise09_01 rectangle2 = new Exercise09_01(3.5, 35.9);
System.out.println("The area of a 3.5 x 35.9 Rectangle is " + rectangle2.getArea());
System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
rectangle2.getPerimeter());
}
}
Thanks for all the help and this is the code that passes through the compiler. Just leaving it here for future visitors.

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

My code outputs incorrectly

I am trying to make a program that calculates the area of a triangle given the values for all three sides. When I run my program with my runner file my area comes out to " 0.0"
Here is the classes full code (also I know I did the same code for setSides and triangle but my instructor gave us this shell and I didn't know what to put in there)
import java.util.Scanner;
import java.lang.Math.*;
public class Triangle
{
private int sideA;
private int sideB;
private int sideC;
private double theArea;
private double s;
private double perimeter;
public Triangle()
{
sideA = 1;
sideB = 1;
sideC = 1;
}
public Triangle(int a, int b, int c)
{
sideA = (int) a;
sideB = (int) b;
sideC = (int) c;
}
public void setSides(int a, int b, int c)
{
sideA = (int) a;
sideB = (int) b;
sideC = (int) c;
}
private double calcPerimeter()
{
double perimeter = sideA + sideB + sideC;
return perimeter;
}
private double calcArea()
{
double s = calcPerimeter() / 2;
double theArea = (Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC)));
return theArea;
}
public void print()
{
System.out.println("Area == " + theArea);
}
}
I did an system out on your statement. What you are using is not an subtract operator. Please fix that. It will work. Also define the permiter.
System.out.println((int)'–');
output:
8211
Is it possible that you copied some of your source code from a document that isn't a simple text document?
If so, then your problem is that your minus signs are not the proper character. Try re-typing them in a text editor.
ED: Also, a minus sign should be surrounded by spaces. When I first looked at this, it threw me.
In your revised code, you can be square rooting a negative number, which would through you in a really bad state.
Remove:
private double perimeter;
And change:
private double calcArea()
{
double s = perimeter / 2;
double theArea = (Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC)));
return theArea;
}
To:
private double calcArea()
{
double s = calcPerimeter() / 2;
double theArea = (Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC)));
return theArea;
}
Here is what is happening. You declare a private double called perimeter. Later in the code you once again declare a double called perimeter. When you do this, things get really confusing! Make sure you only declare variables with the same name ONCE, and reference them thereafter.

coneVolume Method returning zero

I can't seem to figure out why my coneVolume method is returning zero when all of my other methods are working properly.
import java.util.Scanner;
public class P56old{
public static double sphereVolume(double r){
double sphereVolume = (4/3)*(Math.PI)*(Math.pow(r, 3));
return sphereVolume;
}
public static double sphereSurface(double r){
double sphereSurface = 4 * (Math.PI) * Math.pow(r, 2);
return sphereSurface;
}
public static double cylinderVolume(double r, double h){
double cylinderVolume = (Math.PI) * (Math.pow(r, 2)) * h;
return cylinderVolume;
}
public static double cylinderSurface(double r, double h){
double cylinderSurface = 2 * (Math.PI) * (Math.pow(r, 2)) + 2 * Math.PI * r * h;
return cylinderSurface;
}
public static double coneVolume(double r, double h){
double coneVolume = (1/3) * Math.PI * (Math.pow(r,2)) * h;
return coneVolume;
}
public static double coneSurface(double r, double h){
double s = Math.sqrt(Math.pow(r,2) + Math.pow(h, 2));
double coneSurface = Math.PI * Math.pow(r,2) + Math.PI * r * s;
return coneSurface;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Please give the radius: ");
double r = in.nextDouble();
System.out.print("Please give the height: ");
double h = in.nextDouble();
double coneVolume = coneVolume(r,h);
double sphereVolume = sphereVolume(r);
double sphereSurface = sphereSurface(r);
double cylinderVolume = cylinderVolume(r,h);
double cylinderSurface = cylinderSurface(r,h);
double coneSurface = coneSurface(r,h);
System.out.println("The Sphere Volume is " + sphereVolume);
System.out.println("The Sphere Surface is " + sphereSurface);
System.out.println("The Cylinder volume is " + cylinderVolume);
System.out.println("The Cylinder Surface is " + cylinderSurface);
System.out.println("The Cone Volume is " + coneVolume);
System.out.println("The Cone Surface is " + coneSurface);
}
}
I'd appreciate any insight on the matter, and any critique is appreciated. I think it may have to do with all the public classes and maybe another method is affecting the coneVolume method but I just don't know enough about methods at the moment to fix the issue at hand.
When you do 1/3, it does integer division, resulting in 0 (the remainder is 1). Multiplying by 0 gives 0. Do 1.0/3.0 instead, and it will correctly compute an approximation to one third.

Categories

Resources