Java: No compile errors, but my output is wrong - java

My assignment was to create a class named MyRectangle to represent rectangles.
The required data fields are width, height, and color. Use double data type for width and height, and a String for color. Then Write a program to test the class MyRectangle. In the client program, create two MyRectangle objects. Assign a width and height to each of the two objects. Assign the first object the color red, and the second, yellow. Display all properties of both objects including their area.
I've written everything out and am getting no errors, but my output stays the same no matter what values I put in for the rectangles.
package MyRectangle;
public class MyRectangle{
private double width = 1.0;
private double height = 1.0;
private static String color = "black";
public MyRectangle(double par, double par1){
width ++;
height ++;
}
//Parameters for width, height, and color //
public MyRectangle(double widthParam, double heightParam, String colorParam){
width = widthParam;
height = heightParam;
color = colorParam;
width ++;
height ++;
}
// Accessor width //
public double getWidth(){
return width;
}
public void setWidth(double widthParam){
width = (widthParam >= 0) ? widthParam: 0;
}
// Accessor height //
public double getHeight(){
return height;
}
public void setHeight(double heightParam){
height = (heightParam >= 0) ? heightParam: 0;
}
// Accessor color //
public static String getColor(){
return color;
}
public static void setColor(String colorParam){
color = colorParam;
}
// Accessor area //
public double findArea(){
return width * height;
}
}
class MyRectangleTest {
#SuppressWarnings("static-access")
public static void main(String args[]) {
// Create triangle and set color value to red //
MyRectangle r1 = new MyRectangle(5.0, 25.0);
r1.setColor("Red");
System.out.println(r1);
System.out.println("The area of rectangle one is: " + r1.findArea());
// Create triangle and set color value to yellow //
MyRectangle r2 = new MyRectangle(3.0, 9.0);
r2.setColor("Yellow");
System.out.println(r2);
System.out.println("The area of rectangle one is: " + r2.findArea());
}
}

The constructor you are using makes no sense.
You ignore the passed rectangle dimensions, so you'll always get a 2 by 2 rectangle:
private double width = 1.0;
private double height = 1.0;
...
public MyRectangle(double par, double par1){
width ++;
height ++;
}
It should be something like :
public MyRectangle(double width, double height){
this.width = width;
this.height = height;
}
In addition, the color member shouldn't be static, unless you want all your rectangles to have the same color.
One last thing - in order for System.out.println(r1); and System.out.println(r2); to Display all properties of both objects, you must override toString():
#Override
public String toString()
{
return "width = " + width + " height = " + height + " color = " + color;
}

There are a couple of things wrong here:
The color member is static, which means in belongs to the class, instead of each instance having its own.
The (double, double) constructor doesn't store the height and the width.
Both constructors increment the height and the width, for no good reason.
Since you don't have a default constructor, the default values for the members are redundant - there's no flow where they won't be overwritten.
To sum it up, your class should be declared more or less like this:
public class MyRectangle {
private double width;
private double height;
private String color;
private static final String DEFAULT_COLOR = "black";
public MyRectangle(double width, double height) {
this (width, height, DEFAULT_COLOR);
}
public MyRectangle(double width, double height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
// Rest of the required methods
}

Related

Code works fine, just want to know why I don't need a set method for Perimeter and Area but for width and length

import java.util.Scanner;
public class Rectangle {
private double length, width;
Scanner scan = new Scanner(System.in);
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
public void setLength(double l){
length = l;
}
public double getLength(){
return length;
}
public void setWidth(double w){
w = width;
}
public double getWidth(){
return width;
}
public double getArea(){
return length*width;
}
public double getPerimeter(){
return ((2*length) + (2*width));`enter code here`
}
}
Why don't I need a set method for Area and Perimeter? Also does it matter if you make the code this.length = length as compared to length = l?
Think about it this way: how would you implement a setter for the perimeter or the area property?
There is no good way of doing it that would make reasonable sense to users of your class: let's say the width is 10 and the height is 7, and a call arrives to set the perimeter to 24. Would you adjust the height, the width, or both in order to satisfy the new value of the perimeter? There is no usable solution to this problem.
Area and Perimeter are so-called calculated properties, i.e. properties computed from values of settable properties. That is why neither area nor perimeter can have a setter.

declare 2d variable Java

I am wondering whether it is possible to assign a value to a variable that would point to some exact position in the 2d Array in Java.
I am accessing array element through
imageMatrix[width][hight].getColor1()
and since I am considering different scenarios, it would be easier to declare [width][high] by eg. n1=[2][1] and then call
imageMatrix(n1).getColor1()
Is it somehow possible? Thanks!
You can define a class Coordinate that contains the width and height of a cell of your 2d array. Then use an instance of this class to your imageMatrix() method.
Something like:
public clas Coordinate{
private int height;
private int width;
/*Accessors and constructors...*/
}
You can define ImageMatrix and Point as class.
For setting and getting color of each point you can create method inside Point class.
Here we are storing each point in a list so that we can access them in future.
import java.util.ArrayList;
public class ImageMatrix {
Point point;
public ImageMatrix(Point point){
this.point = point;
}
public static void main(String[] args) {
//to set color and store each point into a list
ArrayList<Point> pointList = new ArrayList<>();
//creating 9 points with different color
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Point point = new Point(i,j);
point.setColor("color"+i+j);
pointList.add(point);
}
}
//to get color from each point
for(Point point : pointList){
System.out.println("color of point " + point.height +" and " + point.width +" is : " + point.getColor());
}
}
}
class Point{
public int height;
public int width;
public String color;
public Point(int height, int width){
this.height = height;
this.width = width;
}
public void setColor(String color){
this.color = color;
}
public String getColor(){
return this.color;
}
}

Variable isn't initialized when trying to use methods

calculateArea(Length, Height, Width);
double area;
calculateCost(area);
}
public static double calculateArea(int l, int h, int w) {
//Variables
double area;
//Length = l;
// Height = h;
//Width = w;
//Find the area
area = l * h * w;
//returns area outside the method
return area;
}
public static void calculateCost(double ar)
PaintCalculator.java:39: error: variable area might not have been initialized
calculateCost(area);
^
1 error
I can't figure out why it isn't initialized when I returned the value for area in the calculateArea method. I've tried declaring and initializing the double area; above calculateCost, but I'm stumped as to why area inside the calculateCost is set to double the area.
You must assign your variable area to your function calculateArea:
double area = calculateArea(Length, Height, Width);
calculateCost(area);
the value for area is currently null, set it equal to something or use the other method you have shown to calculate the area

Writing an XYRectangle Class in Java

I have the following class to write:
Write a class named XYRectangle_LastName, where LastName is replaced with your last name.. The XYRectangle_LastName class should have the following fields:
An XYPoint named TopLeft. This stores the location of the topleft corner of a Rectangle.
A double named Length. This stores the length of the rectangle.
A double named Width. This stores the width of the rectangle.
The XYRectangle class should have the following methods:
A no-argument constructor that randomly determines the top left corner of the rectangle. The values for x and y should be between -10 and 10. Also, it chooses a random width and length for the rectangle with values between 5 and 10.
A 3 argument constructor that takes an XYPoint for the top left corner, a length, and a width.
A get method for length, width, topLeft, topRight, bottomLeft, and bottomRight
A set method for length, width, and topLeft
A boolean method named isInside that takes an XYPoint and determines if it is inside this rectangle.
A method named reflectX that returns a rectangle that has been reflected over the x-axis.
A method named reflectY that returns a rectangle that has been reflected over the y-axis.
This is the code I have so far:
public class XYRectangle {
private XYPoint topLeft;
private double length;
private double width;
public XYRectangle() {
Random rnd = new Random();
int x = (rnd.nextInt(21) - 10);
int y = (rnd.nextInt(21) -10);
XYPoint topLeft = new XYPoint(x, y);
int width = (rnd.nextInt(5) + 5);
int height = (rnd.nextInt(5) + 5);
}
public XYRectangle(XYPoint topLeft, double length, double width) {
this.topLeft = topLeft;
this.length = length;
this.width = width;
}
public double getLength() { return this.length; }
public void setLength(double length) { this.length = length; }
public double getWidth() { return this.width; }
public void setWidth(double width) { this.width = width; }
public XYPoint getTopLeft() { return this.topLeft; }
public void setTopLeft(XYPoint topLeft) { this.topLeft = topLeft; }
I'm having trouble with the topRight, bottomLeft, and bottomRight get methods and the reflect methods. I'm not even sure if the code I've written so far is write. Could anyone help and tell me how to proceed and if I've been doing something wrong?
You don't have the information about topRight, bottomLeft, and bottomRight, but having the topLeft corner and the width, length, it totally defines the other points:
topRight = new XYPoint(topLeft.getX() + length, topLeft.getY());
bottomRight = new XYPoint(topLeft.getX() + length, topLeft.getY() + width);
bottomLeft = new XYPoint(topLeft.getX(), topLeft.getY() + width);
You can decide to store this information when you construct your object or to calculate it each time the get method is called.
About the empty constructor, you are calling it "corner" when it should be called:
public XYRectangle(){
//code here
}
Usually when we override constructors we call the base constructor like this:
public XYRectangle(){
Random rnd = new Random();
int x = (rnd.nextInt(21) - 10);
int y = (rnd.nextInt(21) -10);
XYPoint topLeft = new XYPoint(x, y);
int width = (rnd.nextInt(5) + 5);
int height = (rnd.nextInt(5) + 5);
this(topLeft, width, height)
}
I hope you can figure out the reflection methods yourself. ;)

New to Java: SuperClass and SubClass

I am fairly new to Java and I am learning about Inheritance. I am trying to create a subclass called BetterRectangle under the superclass Rec1.
Rec 1 gets the x and y coordinates (location) and also gets the width and height (size) of the rectangle. BetterRectangle calculates the perimeter and area of the rectangle.
I get errors in the main method. It cannot find any of the symbols (i.e. cannot find rec1.getHeight(20) symbol).
public class Rec1 {
private double x;
private double y;
private double width;
private double height;
public void setLocation(double xCord, double yCord) {
x = xCord;
y = yCord;
}
public void setSize(double h, double w) {
height = h;
width = w;
}
public double getHeight(double h) {
return height;
}
public double getWidth(double w) {
return width;
}
}
public class BetterRectangle extends Rectangle {
public BetterRectangle(int x, int y, int width, int height) {
super(x, y, width, height);
super.setLocation(x, y);
super.setSize(width, height);
}
public double calcPerimeter() {
return super.getHeight() * 2 + super.getWidth() * 2;
}
public double calcArea() {
return super.getHeight() * super.getWidth();
}
}
Look closely:
Rectangle Rec1 = new Rectangle();
Rec1.getHeight(20);
The type of Rec1 is Rectangle. But the Rectangle class doesn't have a getHeight method. Maybe you wanted this:
Rec1 rec1 = new Rectangle();
rec1.getHeight(20);
Notice that I renamed the variable to rec1, and changed its type.
class BetterRectangle is extending Rectangle in your sample code. So here BetterRectangle would be child and Rectangle would be parent. Now BetterRectangle uses super keyword to access getHeight,getWidth etc...functions. since these functions are not present in Rectangle class it is giving compilation Error.
Instead of extending Rectangle class extend Rec1 class in BetterRectangle and then run the main Class Rectangle. This should work.
Look carefully here
Rectangle BetterRectangle = new Rectangle();
Rectangle Rec1 = new Rectangle();
You are declaring variables of type Rectangle instead of your own classes. I can't see your import statements but you are likely creating types of java.awt.rectangle. You're mixing up variable types and variable names. When creating instances of your own classes it should look like this:
Rec1 mySimpleRec = new Rec1();
BetterRectangle myBetterRec = new BetterRectangle()
When declaring things put them in this order "Type variableName = new Type()" or "Class variableName = new Class()".

Categories

Resources