Implement constructors with variables from another class? - java

I'm a java beginner and would like some help implementing my constructors
for example
public Class WidthLenth {
private double width;
private double length;
public WidthLength(double width, double length) {
this.width = width;
this.length = length;
}
public double getWidth() {
return width;
}
public double getLength() {
return length;
}
and in another class
public Class Rectangle {
private WidthLength widthLength <-- there is a uni-directional relationship here
private String color
I need to the constructor to be in this format
public Rectangle(double width, double length, String color) {
}
So the method
public getWidthLenth() {
}
would work.
how would I implement this constructor?

You just create a new object of WidthLength in the constructor.
public Rectangle(double width, double length, String col)
{
widthLength = new WidthLength(width, length);
color = col;
}

try this:
public Rectangle(double width, double length, String color) {
this.widthLength = new WidthLength(width, length);
this.color = color;
}
public WidthLength getWidthLength() {
return this.widthLength;
}

Related

Having trouble with "Rectangles"

Create a class Rectangle with instance variables length and width to
have default value of 1 for both of them. The class should have
suitable set and get methods for accessing its instance variables. The
set methods should verify that length and width are assigned a
value that is larger than 0.0 and is lesser than 20.0, Provide
suitable public methods to calculate the rectangle’s perimeter and
area. Write a suitable class "RectangleTest" to test the Rectangle
class.
What I came up with:
package rectangle;
public class Rectangle
{
private double width;
private double length;
public Rectangle()
{
width=1;
length=1;
}
public Rectangle(double width, double length)
{
this.width = width;
this.length = length;
}
public void setWidth(float width)
{
this.width = width;
}
public float getWidth()
{
return (float) width;
}
public void setLength(float length)
{
this.length = length;
}
public float getLength()
{
return (float) length;
}
public double getPerimeter()
{
return 2 * (width + length);
}
public double getArea()
{
return width * length;
}
}
package rectangle;
import java.util.Scanner;
public class RectangleTest extends Rectangle
{
public static void main(String[] args)
{
Scanner RectangleTest = new Scanner(System.in);
System.out.print("Length: ");
float lengthInput = RectangleTest.nextFloat();
System.out.print("Width: ");
float widthInput = RectangleTest.nextFloat();
Rectangle rectangle = new Rectangle (lengthInput, widthInput);
System.out.printf("Perimeter: %f%n",
rectangle.getPerimeter());
System.out.printf("Area: %f%n",
rectangle.getArea());
}
}
Code is fine, it's just I am not sure how to implement the between 0 - 20 without breaking everything and have tried different things.
I'd check it and throw an IllegalArgumentException if the value isn't valid, e.g.:
public void setLength(float length) {
if (length <= 0f || length >= 20.0f) {
throw new IllegalArgumentException("Invalid length " + length);
}
this.length = length;
}

How to update an object attribute in Priority Queue Java?

If I have a class with four attributes and their getters and setters:
public class Shape {
private int id;
private int length;
private int width;
private int height;
Shape(int id, int length, int width, int height){
this.id = id;
this.length = length;
this.width = width;
this.height = height;
}
public int getId() {
return id;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
In my main class, I have a PriorityQueue of shapes ordered by height. My question is: how can I find an object in my PriorityQueue and update its length and width?
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
Comparator<Shape> comparator = Comparator.comparing(Shape::getHeight);
PriorityQueue<Shape> shapes = new PriorityQueue<Shape>(comparator);
shapes.add(new Shape(1,10,10,10);
shapes.add(new Shape(2,20,20,20);
shapes.add(new Shape(3,30,30,30);
}
//What I want to do is
for(each element s in shapes){
if(s.equals(shape){
//update the length and width of element s in the priority queue
}
}
}
PS: I must implement it as a PriorityQueue

How to create an object from data in a file and assign it to an array?

I need to take information from a file and create them into objects and put them into an array so I can compare the areas of the objects and list in the array which object has the largest area and its location in the array.
I'm confused on how I take the information from the file and create each one into a object (circle or rectangle) and then assign that object into an array after it has been created. I think my other classes are fine, I'm just stuck on finishing the driver.
Normally, I would do something like Circle c1 = new Circle(); to create a new object, but how do I do that from a file with predefined information and assign it to an array?
Data:
“CIRCLE”, 1, “blue”, true
“RECTANGLE”, 1, 2, “blue”, true
“RECTANGLE”, 10, 2, “red”, true
“CIRCLE”, 2, “green”
“RECTANGLE”
“CIRCLE”
Driver:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("C:/Users/Charles/Desktop/GeometricObjectsData.txt"));
ArrayList<GeometricObject> list = new ArrayList<GeometricObject>();
while (input.hasNext()) {
String line = input.nextLine();
System.out.println(line);
}
}
}
GeometricObject:
public abstract class GeometricObject {
//class variables
private String color;
private boolean filled;
//constructors
public GeometricObject() {
super();
color = "white";
filled = false;
}
public GeometricObject(String color, boolean filled) {
super();
this.color = color;
this.filled = filled;
}
//mutators
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
//user-defined methods
public abstract double getArea();
public abstract double getPerimeter();
#Override
public String toString() {
return super.toString() + " \tColor=" + this.getColor() + " \tFilled=" + this.isFilled();
}
}
Circle:
public class Circle extends GeometricObject {
//class variables
private double radius;
//constructors
public Circle() {
super();
radius = 1;
}
public Circle(double radius, String color, boolean filled) {
super(color, filled);
this.radius = radius;
}
//mutators
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
//user-defined methods
#Override
public double getArea() {
//area of a circle
return (radius * radius * Math.PI);
}
#Override
public double getPerimeter() {
//perimeter of a circle
return (2 * radius * Math.PI);
}
#Override
public String toString() {
return super.toString() + "\nCircle: Radius=" + this.getRadius();
}
}
Rectangle:
public class Rectangle extends GeometricObject {
//class variables
private double height;
private double width;
//constructors
public Rectangle() {
super();
height = 1;
width = 1;
}
public Rectangle(double height, double width, String color, boolean filled) {
super(color,filled);
this.height = height;
this.width = width;
}
//mutators
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
//user-defined methods
#Override
public String toString() {
return super.toString() + "\nRectangle: Height=" + this.height + "\tWidth=" + this.width;
}
#Override
public double getArea() {
return (height * width);
}
#Override
public double getPerimeter() {
return (2 * height + 2 * width);
}
}
In your text file, you have special quotes around your shape items. This will make your life more difficult, so you should change that, if possible
Example of how to make objects (from your main method):
while (input.hasNext()) {
String line = input.nextLine();
System.out.println(line);
String[] parts = line.split(",");
if (parts[0].indexOf("Circle") != -1) {
Circle c = new Circle();
// ... parse the rest of the attributes to set up your circle
} else if ... // fill in the other shape cases
}

Java how to implement and design an abstract class

I've run into a design problem in my java code. My application uses missiles, and there are different types of missiles that all work identical except they have 3 unique attributes. The constructor of a missile must know these attributes. I decided to make missile an abstract class, but I can't assign values to protected variables in a subclass outside of a method/constructor. Also I can't declare the variables in the constructor, because I must make the call to the super-constructor first thing.
How can I be smart about this problem?
public abstract class Missile {
private int x, y;
private Image image;
boolean visible;
private final int BOARD_WIDTH = 390;
protected final int MISSILE_SPEED;
protected final int MISSILE_HEIGHT;
protected String file;
public Missile(int x, int y) {
ImageIcon ii =
new ImageIcon(this.getClass().getResource(file));
image = ii.getImage();
visible = true;
this.x = x;
this.y = y - Math.floor(MISSILE_HEIGHT/2);
}
public Image getImage() {
return image;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isVisible() {
return visible;
}
public void move() {
x += MISSILE_SPEED;
if (x > BOARD_WIDTH)
visible = false;
}
}
And there is an ideal implementation of a subclass, except it doesn't work. (it can't recognize the protected variables). What do I do?
public class Laser extends Missile {
MISSILE_SPEED = 2;
MISSILE_HEIGHT = 5;
file = "laser.jpg";
public Laser(int x, int y) {
super(x, y);
}
}
I think the best way to do what you want it to do is make abstract methods in Missile that the subclasses have to implement. For example, add these to Missile:
public abstract int getMissileSpeed();
public abstract int getMissileHeight();
public abstract int getFileName();
Then your subclass has to implement it, and you can make it constant like so:
public class Laser extends Missile {
public Laser(int x, int y) {
super(x, y);
}
public int getMissileSpeed() {
return 2;
}
public int getMissileHeight() {
return 5;
}
public String getFileName() {
return "laser.jpg";
}
}
edit: And then of course anywhere that you want to retrieve the constant value you just call those methods.
Change the base class fields and constructors to
protected final int speed;
protected final int height;
public Missile(int x, int y, int speed, int height, String file) {
ImageIcon ii =
new ImageIcon(this.getClass().getResource(file));
image = ii.getImage();
visible = true;
this.speed = speed;
this.height = height;
this.x = x;
this.y = y - Math.floor(height/2);
}
And the subclass to:
public class Laser extends Missile {
public Laser(int x, int y) {
super(x, y, 2, 5, "laser.jpg");
}
...
}
The attributes are already in the base class, so they must not be redefined in the subclass. All-uppercase naming is reserved to constants in Java.
I'm not sure if missile needs to be an abstract class, but I think something like this might be what you're going for:
public abstract class Missile {
private int x, y;
private Image image;
boolean visible;
private final int BOARD_WIDTH = 390;
protected final int MISSILE_SPEED;
protected final int MISSILE_HEIGHT;
public Missile(int x, int y, int speed, int height, String file) {
MISSILE_SPEED = speed;
MISSILE_HEIGHT = height;
ImageIcon ii = new ImageIcon(this.getClass().getResource(file));
image = ii.getImage();
visible = true;
this.x = x;
this.y = y - Math.floor(MISSILE_HEIGHT/2);
}
}
public class Laser extends Missile {
public Laser(int x, int y) {
super(x, y, 2, 5, "laser.jpg");
}
}
Create an interface and put all your final fields in it.
Now implement this interface within Missile and Laser both. At least that would solve the issue of access.

Drawing Issues - Drawing a compound shape from other shapes

So I have an assignment for University. The concept was that we were to complete some class hierarchy stuff. Basically it was stuff to allow us to draw different shapes.
I can successfully draw each shape; where I need it to be and how big I need it to be, like required... the part I'm having trouble on is this compound hierarchy.
Basically we're supposed to have a new class called Compound.java and extending from that we are supposed to have three other classes, House, tree, and earth; each of which are supposed to take the shape objects we created (Rectangle, Square, Line, Oval and Circle) and draw the required pictures as denoted by the class name.
Where I am having the problem is in the house class; for example: I can get it to draw one rectangle but when I try to get it to draw the second rectangle after, it basically forgets about the first and only draws the second!
We haven't had any practice with the Graphics stuff so I don't know any methods or anything that I can call to draw then continue in the House constructor.
I understand why it overwrites the first rectangle, when the House constructor is called, it runs through all the stuff in the constructor, then goes back up to the Compound.java and draws it using the draw(Graphics g) method....
But I don't know how to fix it! Any help would be appreciated... it's due tomorrow.
Here's all the code:
Shape.java:
import java.awt.*;
public abstract class Shape {
int initX, initY;
Color fillColour;
public Shape() {
initX = 0;
initY = 0;
}
public Shape(int x, int y) {
initX = x;
initY = y;
}
public void setInitX (int x) {
initX = x;
}
public void setInitY (int y) {
initY = y;
}
public abstract void draw(Graphics g);
public abstract double Area();
public abstract double Perimeter();
public void Move(int deltaX, int deltaY){
//future work
}
}
ClosedShape.java :
import java.awt.Graphics;
public abstract class ClosedShape extends Shape {
boolean polygon;
int numPoints;
int[] xVertices;
int[] yVertices;
int x,y,width, height;
public ClosedShape(boolean isPolygon, int numPoints) {
super(0,0);
this.polygon = isPolygon;
this.numPoints = numPoints;
}
public ClosedShape(boolean isPolygon, int numPoints, int[] x, int[] y) {
super(x[0],y[0]);
this.polygon = isPolygon;
if (isPolygon) {
this.numPoints = numPoints;
xVertices = new int[numPoints]; // error check? if x.length == numPoints
for (int i = 0; i < x.length; i++) { // make copy of array: why?
xVertices[i] = x[i];
}
yVertices = new int[numPoints]; // error check? if y.length == numPoints
for (int i = 0; i < y.length; i++) { // make copy of array
yVertices[i] = y[i];
}
}
else { // its an oval - define bounding box
this.numPoints = 4;
this.x = x[0];
this.y = y[0];
width = x[1];
height = y[1];
}
}
public void setXYCoords(int[] x, int[] y){
this.xVertices = x;
this.yVertices = y;
}
// Gives access to the width attribute
public void setWidth(int width){
this.width = width;
}
// Gives access to the height attribute
public void setHeight(int height) {
this.height = height;
}
public void draw(Graphics g) {
if (polygon) {
g.drawPolygon(xVertices, yVertices, numPoints);
}
else {
g.drawOval(x, y, width, height);
}
}
public abstract double Area();
public abstract double Perimeter();
}
Rectangle.java :
public class Rectangle extends ClosedShape
{
public Rectangle(int x, int y, int width, int height)
{
super(true, 4);
setWidth(width);
setHeight(height);
int [] arrayX = new int[4];
arrayX[0] = x;
arrayX[1] = (x+width);
arrayX[2] = (x+width);
arrayX[3] = x;
int [] arrayY = new int[4];
arrayY[0] = y;
arrayY[1] = y;
arrayY[2] = y+height;
arrayY[3] = y+height;
setXYCoords(arrayX, arrayY);
}
public double Area()
{
return 0;
}
public double Perimeter()
{
return 0;
}
}
Compound.java :
import java.awt.*;
import java.awt.Graphics;
public class Compound
{
boolean polygon;
int[] xVertices;
int[] yVertices;
int initX, initY;
Color fillColour;
public void setXYCoords(int[] x, int[] y)
{
this.xVertices = x;
this.yVertices = y;
}
public void draw(Graphics g)
{
if (polygon) {
g.drawPolygon(xVertices, yVertices, 4);
}
else {
g.drawOval(1, 1, 1, 1);
}
}
}
House.java :
import java.awt.*;
import java.awt.Graphics;
public class House extends Compound
{
public House(int x, int y, int width, int height)
{
int [] arrayX = new int[4];
arrayX[0] = x;
arrayX[1] = (x+width);
arrayX[2] = (x+width);
arrayX[3] = x;
int [] arrayY = new int[4];
arrayY[0] = y;
arrayY[1] = y;
arrayY[2] = y+height;
arrayY[3] = y+height;
setXYCoords(arrayX, arrayY);
this.polygon = true;
Rectangle house = new Rectangle(x, y, width, height);
int [] arrayXTwo = new int[4];
arrayXTwo[0] = x+(width/4);
arrayXTwo[1] = x+(2*(width/4));
arrayXTwo[2] = x+(2*(width/4));
arrayXTwo[3] = x+(width/4);
int [] arrayYTwo = new int[4];
arrayYTwo[0] = y+(height/4);
arrayYTwo[1] = y+(height/4);
arrayYTwo[2] = y+height;
arrayYTwo[3] = y+height;
setXYCoords(arrayXTwo, arrayYTwo);
this.polygon = true;
Rectangle door = new Rectangle(x, y, width, height);
}
}
From your sample code, there is no way that to "add" any shapes to the Compound class. From your description, Compound should be a "container" of shapes. Something more along the lines of...
public class Compound
{
private List<Shape> shapes;
public Compound() {
shapes = new ArrayList<Shape>(25);
}
public void addShape(Shape shape) {
shapes.add(shape);
}
public Iterable<Shape> getShapes() {
return shape;
}
public void draw(Graphics g) {
for (Shape shape : shapes) {
shape.draw(g);
}
}
}
Now you need to decide, where is it best to associate the Color with the Shape should it be defined for the shape itself? That means you can't reuse the shape. Or with the Compound shape?

Categories

Resources