So, I have a twoparter question. The first part I did, which was creating an interface and then utilizing that interface in two different classes. However the second part of the question has me stumped. I'm not understanding the logic aspect of it. It feels as though the question order should be in reverse. This is two things I need to do to finish up the last portion of the assignment. If anyone here could give me just some tiny guidance as to to the direction I should be taking I'd greatly appreciate it.
Part II:
(1)Create an array of Calculatable objects in main and call the sumCalculate method.
For the most part I understand this, I already began doing it but decided to start working on (2) since that was way more difficult for me. It's basically creating an array of Calculatable objects of a certain size ( I chose 5) and populating it with different calculatable objects ( could be rectangles or squares in my example). But the second half of this question confuses me? Am I calling the sumCalculate method that I'm GOING to be making in question 2? Or am I calling it before I even make the (2) method.
(2)Make a method that accepts an array of Calculatable objects and sums up the values that are returned by each object's call to calculate.
What I'm trying to figure out here in question (2) is this. When it asks me to make the method? Does this mean that I'm making a new method in interface called sumCalc for example, that has parameters that accepts an array of calculatable objects? And then as far as summing up the values that are returned. I'd assume that I'd be adding the calculation double that is returned by calculate methods.
I'd ask my professor but this professor I decided to take has made it a habit of being excessively difficult to reach. Sorry to bother you guys with what is most likely an elementary and not difficult question.
interface Calculatable {
public double calculate(int x);
}
class square implements Calculatable {
public double side;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate(int x) {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
return calculation;
}
}
public class rectangle implements Calculatable {
public double length;
public double width;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate(int x) {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
return calculation;
}
public static void main(String [] args){
Calculatable perimeter1 = new rectangle(20.5 , 50);
perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = new rectangle(20.5 , 50);
perimetersums[1] = new rectangle(10 , 25);
}
}
I would create sumCalculate beside main method and be over with it. Lesson is to implement an interface method and use it too.
And beside that I suggest reading Java naming convention and correcting your code accordingly.
The way I understand it you should not change the Interface, especially if the Interface was provided to you!
Just write your sumCalculate below your main method like this
private static double sumCalculate(Calculateable[] c) {
// do your sum up and return the result
}
and call it in your main method like this
double sum = sumCalculate(perimetersums);
few confusion is in my mind.. In the implementation rectangle your are not using the x in the calculate method. I changed the whole class structure a little bit.. Please look.. I think it will help you...
public interface Calculatable {
public double calculate(int x);
public double getPerimeter();
}
public class square implements Calculatable {
public double side;
private double perimeter;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate(int x) {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
this.perimeter=calculation;
return calculation;
}
#Override
public double getPerimeter() {
// TODO Auto-generated method stub
return perimeter;
}
}
public class rectangle implements Calculatable {
public double length;
public double width;
private double perimeter;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate(int x) {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
this.perimeter=calculation;
return calculation;
}
#Override
public double getPerimeter() {
// TODO Auto-generated method stub
return perimeter;
}
}
public class MainMethod {
public static void main(String[] args) {
Calculatable perimeter1 = new rectangle(20.5 , 50);
perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = perimeter1; //new rectangle(20.5 , 50);
perimetersums[1] = perimeter2;// new rectangle(10 , 25);
System.out.println("the sum is= "+sumCalculate(perimetersums));
}
private static double sumCalculate ( Calculatable[] perimetersums)
{
double sum=0.0;
for(int i=0;i<perimetersums.length;i++)
{
Calculatable cal=perimetersums[i];
if(cal!=null)
sum=sum+cal.getPerimeter();
}
return sum;
}
}
I changed the class structure a little bit...
public interface Calculatable {
public double calculate();
}
public class square implements Calculatable {
private final int x=2;
public double side;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate() {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
return calculation;
}
}
public class rectangle implements Calculatable {
private final int x=5;
public double length;
public double width;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate() {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
return calculation;
}
}
public class MainMethod {
public static void main(String[] args) {
Calculatable perimeter1 = new rectangle(20.5 , 50);
// perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
//perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = new rectangle(20.5 , 50);
perimetersums[1] = new rectangle(10 , 25);
System.out.println("the sum is= "+sumCalculate(perimetersums));
}
private static double sumCalculate ( Calculatable[] perimetersums)
{
double sum=0.0;
for(int i=0;i<perimetersums.length;i++)
{
Calculatable cal=perimetersums[i];
if(cal!=null)
{
sum=sum+cal.calculate();
}
}
return sum;
}
}
Related
I already did my assignment with setters and getters (I did this with OOD) however I still don't understand what's the purpose of the two Rectangle methods and if ever I remove the empty Rectangle an error will prompt:
P.S. This is not the full code.
// private double length = 25.0;
private double width = 15.5;
public Rectangle(){
}
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
public void setDimension(double length,double width){
this.length = length;
this.width=width;
}
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
public double area(){
return length * width;
}
public double perimeter(){
return 2 * (length + width);
}
public static void print(){
Rectangle rt = new Rectangle();
Box box = new Box();
System.out.println("The rectangle has a length of " + rt.getLength() + " and a width of " + rt.getWidth() );
System.out.println("The rectangle has an area of "+ rt.area());
System.out.println("The rectangle has a perimeter of "+ rt.perimeter());
box.print();
}
That's the default (no-arg) constructor. Since you have another constructor, Java will not implicitly create it if you don't define it explicitly. Since the first line in your print method calls it, you'll get an error if you remove it.
I have the assignment to use an abstract class as a superclass "Shape". It has three classes that extend that class, Triangle, Circle, and Square. Each class is supposed to compute the area and the perimeter of these shapes. I have things working when I System.out.println(shapeArray[i].computeArea()); in a for loop. But when I try and call the toString method from the child classes in that for loop everything returns as "0". I appreciate anybody taking the time to help out, as I am pretty stuck here. I feel like I have read, and re-read threads, and my textbook all day. I feel like there is just some dumb mistake here that I cannot see.
Shape.java
public class Circle extends Shape {
private double radius;
final private double PI = 3.14159;
private double circumfrence;
private double area;
Circle(double radius) {
this.radius = radius;
}
#Override
public double computeArea() {
double radSquared = radius * radius;
double area = PI * radSquared;
return area;
}
#Override
public double computePerimeter() {
circumfrence = 2 * PI * radius;
return circumfrence;
}
#Override
public String toString() {
return "Area of Circle: " +area + "\nCircumfrence of Circle: " + circumfrence;
}
}
Triangle.java
public class Triangle extends Shape {
private double side1;
private double side2;
private double side3;
private double area;
private double perimeter;
Triangle (double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
#Override
public double computeArea() {
double s =(side1 + side2 + side3) / 2;
double area= Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
area = this.area;
return area;
}
#Override
public double computePerimeter() {
perimeter = side1 + side2 + side3;
return perimeter;
}
#Override
public String toString() {
return "Area of Triangle: " + area+ "\nPerimeter of Triangle: " + perimeter;
}
}
Circle.java
public class Circle extends Shape {
private double radius;
final private double PI = 3.14159;
private double circumfrence;
private double area;
Circle(double radius) {
this.radius = radius;
}
#Override
public double computeArea() {
double radSquared = radius * radius;
double area = PI * radSquared;
return area;
}
#Override
public double computePerimeter() {
circumfrence = 2 * PI * radius;
return circumfrence;
}
#Override
public String toString() {
return "Area of Circle: " +area + "\nCircumfrence of Circle: " + circumfrence;
}
}
Rectangle.java
public class Rectangle extends Shape {
private double length;
private double height;
private double sumOfLength;
private double sumOfHeight;
private double area;
private double perimeter;
Rectangle(double length, double height) {
this.height = height;
this.length = length;
}
#Override
public double computeArea() {
area = (length * height);
return area;
}
#Override
public double computePerimeter() {
sumOfLength = length * 2;
sumOfHeight = height * 2;
perimeter = sumOfLength + sumOfHeight;
return perimeter;
}
#Override
public String toString() {
return "Area of Rectangle: " +area + "\nPerimeter of Rectangle: " + perimeter;
}
}
ShapeArray.java
public class ShapeArray {
public static void main(String [] args) {
Shape shapeArray[] = new Shape[3];
Circle circ = new Circle(9);
Rectangle rect = new Rectangle(10, 6);
Triangle tri = new Triangle(6, 8, 12);
shapeArray[0] = circ;
shapeArray[1] = rect;
shapeArray[2] = tri;
for (int i = 0; i <= 2; i++) {
System.out.println(shapeArray[i].toString());
}
}
}
Output:
Area of Circle: 0.0
Circumfrence of Circle: 0.0
Area of Rectangle: 0.0
Perimeter of Rectangle: 0.0
Area of Triangle: 0.0
Perimeter of Triangle: 0.0
In you must call in for loop shapeArray[i].computeArea() and shapeArray[i].computePerimeter() before shapeArray[i].toString().
In ShapeArray.java
//other code
for (int i = 0; i <= 2; i++) {
shapeArray[i].computeArea();
shapeArray[i].computePerimeter()
System.out.println(shapeArray[i].toString());
}
//other code
It prints 0 because you don't call calculation of perimeter and area for class instance before print it. But I also recommend reviewing your code that it does not use unnecessary variables.
your class Triangle.computeArea method change the from area = this.area; to this.area=area;
Other class like this.
I am trying to write a code that follows certain criteria regarding Regular Polygons and finding the perimeter and area of the polygon. I have to write three different classes Point2D, RegularPolygon, and Driver. I can get all of the necessary criteria to work fine except for when it comes to using the instance variable center to have the center coordinates x and y. There are two things that use the center in the RegularPolygon code and I can't get them to work. I need to have a Point2D instance variable center that stores the x and y coordinates of the polygon’s center, with default values 0 for both the x and y components of the Point2D object. I also need to have a constructor that creates a regular polygon with the specified number of sides, length of side, and a Point2D object that represents the center of the polygon, in that order. I also need to have A method public String toString()that returns a String representation of the polygon containing the number of sides, side length and center coordinates for this polygon. Call the toString()method on the Point2Dcenter as part of this method. However, when I go to call the toString method in Point2D it comes up as an error. If anyone can help me figure out why I can't get it to work in my code I would greatly appreciate it.
//Code for Point2D
public class Point2D
{
//Instance Variables
private int x;
private int y;
/**
* Constructor for objects of class Point2D, this will initialize
* the instance variables
*/
public Point2D(int xVariable, int yVariable)
{
//Initializes Instance Variables
x = xVariable;
y = yVariable;
}
//Accessor Method for X variable
public int getX() {
return x;
}
//Accessor Method for X variable
public int getY() {
return y;
}
//ToString Method
public String toString() {
return "<" + x + "," + y + ">";
}
//Method that tests if the values of x and y are equal
public boolean equal(Object o) {
if (o instanceof Point2D) {
Point2D c = (Point2D)o;
}
return false;
}
}
//Code for RegularPolygon
public class RegularPolygon
{
// instance variables
private int n; //Number of sides
private double side; //Length of sides
private double x; //Value of X-Coordinate
private double y; //Value of y-Coordinate
private double center;
/**
* No argument constuctor that creates a regular polygon with
* default values
*/
public RegularPolygon()
{
//Intilializes Instance Variables
n=3;
side =1;
x=0;
y=0;
}
/**
* Constructor that creates a regular polygon with a specific number
* of sides, length of side, and a Point2D object that represents the
* center of the polygon.
*/
public RegularPolygon(int n, double side, double x, double y) {
this.n = n;
this.side= side;
this.x = 0;
this.y = 0;
}
//Mututator Methods
public void setN(int nValue) {
n = nValue;
}
public void setSide(double sideValue) {
side = sideValue;
}
public void setX(double xValue) {
x = xValue;
}
public void setY(double yValue) {
y = yValue;
}
//Accessor Methods
public int getN() {
return n;
}
public double getSide() {
return side;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
//Calculates the Perimeter of the regular polygon
public double getPerimeter() {
return n * side;
}
//Calculates the Area of the regular polygon
public double getArea() {
double area = (n * (Math.pow(side,2))) / (4 * (Math.tan(Math.PI/n)));
return area;
}
//To String Method
public String toString() {
return "Number of sides: " + n + ", Side Length: " + side + ", Center Coordinates: "+Point2D.toString(x,y);
}
}
Your toString method in Point2D does not take variables as parameters, yet you call it from RegularPolygon with parameters at the end. But the way you called Point2D uses its toString method like a static method, even though it's not. So you either have to instantiate a Point2D, or make Point2D's toString method static. But the problem with this is that then you have to make your x and y in Point2D static as well. Another problem with making your toString() method static is that you can't override Object's toString method. So I recommend that you do the following:
public String toString() {
return "Number of sides: " + n + ", Side Length: " + side + ", Center Coordinates: "+new Point2D((int)x, (int)y).toString();
}
I'm learning java on my own and I have this code that I'm trying to work through.
Here are the requirements:
Write a class Rectangle that has two double fields width and height, and a method void setDimensions(double w, double h) that assigns its parameter values to these fields.
Then, write the accessor (“getter”) methods double getArea() and double getPerimeter() that compute and return the area and the perimeter length of the rectangle, and a mutator (“setter”) method void scale(double sf) that multiplies the width and the height of the rectangle by the scaling factor sf.
Finish up by writing a proper toString method in your class.
public class Rectangle {
double width;
double length;
/**
*/
public void setDimensions(double width, double length)
{
width = 5;
length = 10;
}
/*
*/
public static double getPerimeter(double width, double length)
{
double perimeter = 2 * (width + length);
return perimeter;
}
/*
*/
public static double getArea(double width, double length)
{
double area = (width * length);
return area;
}
/**
*
*/
public void scale(double sf)
{
sf *= length;
sf *= width;
}
public String toString()
{
System.out.println("The length is: " + length);
System.out.println("The width is: " + width);
getArea(width, length);
getPerimeter(width, length);
return "The area is:" + area;
return "The perimeter is:" + perimeter;
}
}
With that being said, I am confused with how to format the toString method. Is this toString method simply supposed to print out the values of the area, perimeter, sf, etc? Or am I supposed to return a string of some sort(Sorry I am new I don't really understand completely)
Also, I don't think I have my SF method working as it should be. Should the method have SF initialized in the method?
Thanks
Usually, the toString method is a human readable string outputting the properties/values of your object.
#Override
public String toString() {
String myStr= "{length: " + getLength() + ", width: " + getWidth() +
", perimiter: " + getPerimiter() + ", area: " + getArea() + "}";
return myStr;
}
// will output something like "{length: 2, width: 3, perimiter: 10, area: 6}"
Also, the scale method should increase length and width by the factor provided as argument.
public void scale(double sf)
{
length *= sf;
width *= sf;
}
// better to create getters and setters and use these.
public void setLength(ln){
this.length = ln;
}
public double getLength(){
return this.length;
}
// same for width, then...
public void scale(double sf){
setLength(getLength()*sf);
setWidth(getWidth()*sf);
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I was given an assignment to perform method overloading in inheritence in java by designing a program that calculates the perimeter of different shapes, i designed code as shown below but when i try to compile, there are errors.
import java.io.*;
import java.util.*;
public class Perimeter {
public double getperimeter(int constant,double pi,double radius){
return(constant*pi*radius);
}
public double getperimeter(int sconstant,double length){
return(sconstant*length);
}
public double getperimeter(int rconstant,double rlength,double widith){
return(rconstant*(rlength+widith));
}
public double getperimeter(double base,double height,double hypotenuse){
return(base+height+hypotenuse);
}
public void main (String args []){
final double pi=22/7;
final int constant=2;
double raduius;
final int sconstant=4;
double length;
final int rconstant=2;
double rlength;
double widith;
double base;
double height;
double hypotenuse;
Perimeter g= new Perimeter();
Scanner s=new scanner(System.in);
System.out.println("Enter The Radius");
g.radius=s.nextDouble();
System.out.println("Enter The Square Length");
g.lenght=s.nextInt();
System.out.println("Enter The Rectangle Lenght");
g.rlength=s.nextInt();
System.out.println("Enter The Rectangle widith");
g.widith=s.nextInt();
System.out.println("Enter The Triangle Base");
g.base=s.nextInt();
System.out.println("Enter The Triangle height");
g.height=s.nextInt();
System.out.println("Enter The Triangle hypotenuse");
g.hypotenuse=s.nextInt();
System.out.println("Perimeter = " + g.getperimeter(constant,pi,radius));
System.out.println("Perimeter = " + g.getperimeter(sconstant,length));
System.out.println("Perimeter = " + g.getperimeter(rconstant,rlength,widith));
System.out.println("Perimeter = " + g.getperimeter(base,height,hypotenuse));
This is a "classic" overriding problem that academics love. (Others involve animals or vehicles.)
Start with a Shape interface:
public interface Shape {
double getPerimeter();
}
Then have subclasses implement it, each in their own way:
public class Rectangle implements Shape {
private double height;
private double width;
public Rectangle(double w, double h) {
this.width = w;
this.height = h;
}
public double getPerimeter() { return 2.0*(this.width + this.height); }
}
public class Circle implements Shape {
private double radius;
public Circle(double r) {
this.radius = r;
}
public double getPerimeter() { return 2.0*Math.PI*this.radius; }
}
You'll be able to do things like this:
List<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Rectangle(1.0, 2.0));
shapes.add(new Circle(10.0));
for (Shape shape : shapes) {
System.out.println(shape.getPerimeter()); // every Shape will do it their own way
}
Add a new Shape implementation and your original code still just works. It's the essence of polymorphism and dynamic binding.
You are defining two methods with same signature within a single class. This is an error. Your methods :
double getperimeter(int constant,double pi,double radius);
double getperimeter(int rconstant,double rlength,double widith);
Also your main method must be declared as static
Hi you should have a the class Perimeter in a different file.
I see missing brackets closing the class Perimeter.
Also like Xavier mentioned you have two methods with the same signature.
You are also reading values from Scanner into Perimeter instance variables and then passing the uninitialized values to the Perimeter methods.
So i would separate the Perimeter class and in the main read the values to local variables and pass them to Perimeter methods.
public void main (String args []){
final double pi=22/7;
final int constant=2;
double raduius;
final int sconstant=4;
double length;
final int rconstant=2;
double rlength;
double widith;
double base;
double height;
double hypotenuse;
Perimeter g= new Perimeter();
Scanner s=new scanner(System.in);
System.out.println("Enter The Radius");
radius=s.nextDouble();
System.out.println("Enter The Square Length");
lenght=s.nextInt();
System.out.println("Enter The Rectangle Lenght");
rlength=s.nextInt();
System.out.println("Enter The Rectangle widith");
widith=s.nextInt();
System.out.println("Enter The Triangle Base");
base=s.nextInt();
System.out.println("Enter The Triangle height");
height=s.nextInt();
System.out.println("Enter The Triangle hypotenuse");
hypotenuse=s.nextInt();
System.out.println("Perimeter = " + g.getperimeter(constant,pi,radius));
System.out.println("Perimeter = " + g.getperimeter(sconstant,length));
System.out.println("Perimeter = " + g.getperimeter(rconstant,rlength,widith));
System.out.println("Perimeter = " + g.getperimeter(base,height,hypotenuse));
You are still unfamiliar with java it seems, hence start help:
The main method is static, that is executed first.
You are using overloaded methods getperimeter, where you can easily mix up int and double. Maybe pick a unique name. Java convention is to use funny camel case: getPerimeter.
import java.util.*;
public class Perimeter {
public static void main(String args[]) {
new Perimeter().execute();
}
public double getperimeter(int constant, double pi, double radius) {
return (constant * pi * radius);
}
public double getperimeter(int sconstant, double length) {
return (sconstant * length);
}
public double getperimeterRLenghtWidith(int rconstant, double rlength, double widith) {
return (rconstant * (rlength + widith));
}
public double getperimeter(double base, double height, double hypotenuse) {
return (base + height + hypotenuse);
}
private void execute() {
final double pi = Math.PI; //22 / 7;
final int constant = 2;
double radius;
final int sconstant = 4;
double length;
final int rconstant = 2;
double rlength;
double widith;
double base;
double height;
double hypotenuse;
Scanner s = new Scanner(System.in);
System.out.println("Enter The Radius");
radius = s.nextDouble();
System.out.println("Enter The Square Length");
length = s.nextInt();
System.out.println("Enter The Rectangle Lenght");
rlength = s.nextInt();
System.out.println("Ener The Rectangle widith");
widith = s.nextInt();
System.out.println("Enter The Triangle Base");
base = s.nextInt();
System.out.println("Enter The Triangle height");
height = s.nextInt();
System.out.println("Enter The Triangle hypotenuse");
hypotenuse = s.nextInt();
System.out.println("Perimeter = " + getperimeter(constant, pi, radius));
System.out.println("Perimeter = " + getperimeter(sconstant, length));
System.out.println("Perimeter = " + getperimeterRLenghtWidith(rconstant, rlength, widith));
System.out.println("Perimeter = " + getperimeter(base, height, hypotenuse));
}
}