Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
public class Wall {
private double width;
private double height;
public Wall() {}
public Wall(double width, double height) {
this.setHeight(height); // using method to set the required fields. //This method is called with unexpected behavior.
this.setWidth(width); // This is not getting called?
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
if (width <= 0) {
this.width = 0;
System.out.println("INVALID VALUE - The width of the wall is updated to :" + 0.0);
} else {
this.width = width;
System.out.println("The width of the wall is updated to :" + width);
}
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
if (height <= 0) {
this.height = 0;
System.out.println("INVALID VALUE - The width of the wall is updated to :" + 0.0);
} else {
this.height = height;
System.out.println("The height of the wall is updated to :" + height);
}
}
public double getArea() {
return width * height;
}
}
//OUTPUT
The width of the wall is updated to :10.0 \\ Expected
INVALID VALUE - The width of the wall is updated to :0.0 \\ not expected
//OUTPUT when parameter order in constructor is reversed
INVALID VALUE - The width of the wall is updated to :0.0 \\expected
The height of the wall is updated to :10.0 \\expected
The goal was to avoid code repetition and I chose to use the setter method in constructor. Also assuming since I am using methods and providing appropriate parameters, the order of the parameter should not matter.
I am not sure if it is supposed to work that way. I see that the method is being called with unexpected behavior.
Few doubts I have regarding the above
Not all methods are getting called in the constructor
Can these setter methods be static and perform operation on the object being created?
What would be the right way to do this?
Thank you
I see that the method is being called with unexpected behavior.
setHeight() actually performs as expected but it is not implemented as you'd expect it. You probably copied it from setWidth() and forgot to change the message so it would print "INVALID VALUE - The width of the wall is updated to : xxx".
the order of the parameter should not matter
The order in which you define the parameters doesn't matter from a technical point of view (unless you have a vargs parameter which needs to be last). However the order of definition leads to the requirement of providing values in the same order when calling the constructor.
Example: Wall(double width, double height) defines the 1st parameter is width and the 2nd is height.
Assume the following:
double width = 5.0;
double height = 7.0;
Wall w = new Wall(height, width);
Here, the names of the parameters don't matter but order does, i.e. w now has a width of 7 and a height of 5 even though the parameters were named otherwise.
What shouldn't matter in most cases is the order in which you call the setters inside the constructor - as long as they're independent.
This means the following 2 should be equivalent:
public Wall(double width, double height) {
this.setHeight(height);
this.setWidth(width);
}
public Wall(double width, double height) {
this.setWidth(width);
this.setHeight(height);
}
When would order matter? If setters were depending on it - not a good style though. Suppose setHeight() would check that height > width. Now if you'd not call setWidth() first setHeight() might behave differently. However, I repeat: this it not good style and should be avoided!
Not all methods are getting called in the constructor
Not sure what you're referring to but constructors don't have to call any method nor do you have to call all the setters there. It really depends on what you want to achieve.
Use constructors for mandatory parameters and setters for mutable ones (and potentially optional). Mutable parameters are those that could be changed after constructing an object, immutable ones should not change - there shouldn't be any setter for those (ideally declare those final and the compiler will complain about setters for those).
Summary:
mandatory + immutable parameters: use constructor only
mandatory + mutable parameters: use constructor which can call setters
optional + mutable parameters: use setters
optional + immutable parameters: use constructor only, potentially via constructor overloads
Can these setter methods be static and perform operation on the object being created?
No, setters should never be static because you'd need to pass the object anyway and thus it's cleaner to just have the setters there.
However, a constructor can call static methods if necessary. Suppose you have a condition to check that width < height which you'd want to call in the constructor and the setters. This could then look like this (simplified and lacking a lot of best practices to keep things simple):
//example of constructor calling the static method
public Wall(double width, double height) {
//check the condition on the input parameters
if( !checkCondition(width, height) ) {
throw new IllegalArgumentException("width >= height");
}
this.setHeight(height);
this.setWidth(width);
}
//example of setter calling the static method
public void setWidth(double width) {
//only set if the condition is met
if(checkCondition(width, this.height) {
//rest of your code
} else {
System.err.println("width would be < height, thus not updating width");
}
}
private static boolean checkCondition(double width, double height) {
return width < height;
}
Related
I’ve never used a separate file for a driver in Java. I’m used to just using a main method. I’ve used separate files in Python but Java is new. Below is my code for each class (“Rectangle” and “Driver”), each from separate files.
Update with the methods changed to static: Don’t pay attention to the change in class names or formatting…I’m just tweaking so it will work with MyProgrammingLab. I still have to add in parameters for length and width being between 0.0 and 20.0 only (easy if-else statements).
import java.util.Scanner;
public class Driver{
public static void main(String[] args) {
Scanner input = new Scanner( System.in);
System.out.print("Enter length of rectangle:");
double length = input.nextDouble();
System.out.print("Enter width of rectangle:");
double width = input.nextDouble();
Rectangle Perimeter = new Rectangle(length, width);
Perimeter.getPerimeter();
Rectangle Area = new Rectangle(length, width);
Area.getArea();
System.out.printf("Area: %.1f, Perimeter: %.1f",Rectangle.getArea(),Rectangle.getPerimeter());
}
}
final class Rectangle {
private static double mLength;
private static double mWidth;
public Rectangle(double length, double width){
mLength = length;
mWidth = width;
}
public double getLength(){
return mLength;
}
public double getWidth(){
return mWidth;
}
public static double getArea(){
double area = mWidth*mLength;
return area;
}
public static double getPerimeter(){
double perimeter = (mWidth*2)+(mLength*2);
return perimeter;
}
}
It makes more sense to create a Rectangle object with it's length & width, so use your overloaded Rectangle constructor by passing the length and width arguments (entered by user) as shown below:
Rectangle Perimeter = new Rectangle(length, width);
the constructor Rectangle() is undefined. Can anyone help?
The important point is that when you have an overloaded constructor like in your Rectangle class (where there are no default i.e., no argument constructors written), you can't create an object using new Rectangle();, this is because compiler doesn't add the default constrcutor automatically for you. I suggest look here for more details on this.
Also, if you wanted to print the Rectangle object with length & width details, you need to override toString() method from java.lang.Object method as shown below:
public class Rectangle {
private double mLength;
private double mWidth;
//add your code here as is
#Override
public String toString() {
return "Rectangle [mLength=" + mLength + ", mWidth=" + mWidth + "]";
}
}
The default constructor is provided by compiler if there are no constructor written explicitly.
But if you explicitly write any constructor in the class, then whenever you call a constructor, be it no-argument or with arguments, it will always look for explicitly defined constructor in class.
And, this is logically correct since, if you want to block creation of objects without any data in it, adding a constructor with argiment is the way to go.
So either explicitly write a no argument constructor in Rectangle and use setter to set its attributs, or just use the argument constructor in your method.
Add to Rectangle.class an empty constructor :
public Rectangle() {
}
Or Use constructor declared with parameters in your method
Rectangle rectangle = new Rectangle(length, width);
In your case you are using the rectangle object wrong.
I think what you looking to do is this :
Rectangle rectangle = new Rectangle(length , width );
System.out.printf("Area: %.1f, Perimeter: %.1f",rectangle.getArea() ,rectangle.getPerimeter());
Recursion always has been something I have a hard time with. I have a test tomorrow and he said there will be some Recursion on the test so I want to be prepared.
The problem I am trying to do says this:
Given a class Rectangle with instance variables width and height, provide a recursive getArea() method. Construct a rectangle whose width is one less than the original and call its getArea method.
So I know that in recursion you end up calling the method inside itself with a simplified rendition. Like, I know somewhere in getArea(int n) I will have to call getArea(n - 1). I am just not sure what to do with width and height.
So I have this:
public int getArea()
{
if (width == 1) {
// Base case here. Not sure what to do for this.
return 1; // Maybe? I'm not sure.
} else {
Rectangle smallerRect = new Rectangle (width - 1);
int smallerArea = smallerRect.getArea();
return smallerArea + height + width;
}
}
Can anyone help me better understand recursion or maybe how to go about thinking through a recursive function? Thanks.
You've got the recursion itself right, with a base case and a recursive case, and a correct reduction of the parameter in the recursive call (except that, as the commenters have noted, you also need to specify the height of the new rectangle). It's only the geometry that needs fixing: height doesn't change during the recursion; what is the area of the base case rectangle, which has got width 1 and height height? And if you are told the area of the rectangle with width width - 1 and height height, how much extra area do you get by adding a strip of width 1 and height height?
For later use: while mathematically correct, this is a terrible way to compute the area of a rectangle, so please don't do this outside of exam/homework situations :-)
Something like this perhaps? It's basically just multiplying width by height with recursion...
public int getArea() {
return getArea(width);
}
private int getArea(int x) {
return x == 0 ? 0 : height + getArea(x-1);
}
public int getArea()
{
if (width == 1) {
// Base case
return height; // Area = width(1)*height
} else {
Rectangle smallerRect = new Rectangle (width - 1, height);
int smallerArea = smallerRect.getArea();
return smallerArea + height;
}
}
I have a class Rectangle laid out like this:
package Inheritance;
/**
*
* #author Jacob
*/
public class Rectangle {
final private int length;
final private int width;
public Rectangle (int l, int w)
{
length = l;
width = w;
}
public int getLength ()
{
return length;
}
public int getWidth ()
{
return width;
}
#Override
public String toString ()
{
return String.format ("Rectangle (%dX%d)", length, width);
}
}
I then need to create class square in the following way:
ad Square:
Square extends Rectangle /
No fields are declared in class Square /
It has a parameterized constructor with (only) one parameter /
The parameter is used to initialize both fields of Rectangle /
It has a method called getSide to expose the side-length of the square /
Override the toString method so that it will return a String of the following form: / Square(side) e.g. Square(4)
The values for the sides are going to be hard coded. Rectangle is going to have a width of 4. In order to get the side of the square to be 4 do I create an instance of rectangle and call the method getWidth and set that as the side length. Thats how I would think to do it but in that case I would only be using one of the fields so, My question is how do I initialize both fields? Can I call Rectangle and make length and width equal or is there some other way I should do it?
Here is the code for my Square class:
public class Square {
public Square (int side)
{
super(side, side);
}
public int getSide ()
{
return side;
}
#Override
public String toString ()
{
return String.format ("Square (%d)", side);
}
}
For the line super(side, side) I get the error constructor Object in class Object cannot be applied to given types. Required no arguments, found int, int. For my return statements I get that it cannot find the variable side.
The values for the sides are going to be hard coded.
I assume that you mean that you will hardcode the values for the width and length when you create a Rectangle and Square object (for example in main()). These values should absolutely not be hardcoded any where in the Rectangle and Square classes.
Rectangle is going to have a width of 4. In order to get the side of the square to be 4 do I create an instance of rectangle and call the method getWidth and set that as the side length.
Not at all. Rather, Square should have its own constructor which calls the Rectangle constructor with the same value for both the width and length:
public Square(int side) {
super(side, side); // Set the width and length to the same value.
}
Hi I had this assignment for my class:
Implement a class named Box that will have the following attributes and methods:
int length, width, height
String color
Constructor method that:
will initialize the 3 integers to 10, 8, 6
will initialize the color to “black”
A setter and getter method for each of the 4 attributes
A method to get the volume of the box
A method to get the surface area of the box (all six sides)
I have all my getters and setters for length width and color. My only problem now is that for volume it will not calculate properly if I set the values to be different.
It only takes the initialized values. Any Ideas to go about it? My code is below for the class. example I could .setLength(7) and instead of printing the total 7*8*6, it prints out the total of 10*8*6.
public class Box
{
private int height = 6;
public void se(int height){
this.height=height;
}
public int getHeight(){
return height;
}
private int width = 8;
public void setWidth(int width){
this.width=width;
}
public int getWidth(){
return width;
}
private int length= 10;
public void setLength(int length){
this.length=length;
}
public int getLength(){
return length;
}
private String color="Black";
public void setColor(String color){
this.color=color;
}
public String getColor(){
return color;
}
private int vol=length*width*height;
public void setVol(int vol){
this.vol=vol;
}
public int getVol(){
return vol;
}
}
Get rid of the vol property and the setVol setter; that's not part of the spec for the class and is the root cause of your problems. Rewrite getVol to compute the volume from the length, width, and height each time it is called.
Your current design doesn't work because vol is not recalculated whenever length, width, or height is changed. You could keep your current set of fields and rewrite the dimension setters to recalculate the vol property each time one is called. That would speed up the getVol getter method at the cost of greater complexity for the class design and slower setter methods. It's a trade-off that you can make or not, as you see fit. However, you need to get rid of the setVol method, because when you set the volume, there's no way to know how to set the dimensions so that the values are consistent.
You need to create a getter function for vol
e.g.
public int getVol () {
vol=length*width*height;
return vol;
}
of course the setting of the intermediate vol is not necessary.
and you could just
return length*width*height;
This ensure that the current vol is always correctly calculated.
This is an instance method from a Rectangle class where we modify the x and y coordinates of the rectangle and its width and height
public void modify(int newX, int y, int width, int h) {
int x = newX;
this.y = y;
width = width;
this.height = height;
}
Rectangle r3 = new Rectangle(0, 0, 10, 10);
r3.modify(5, 5, 50, 50);
System.out.print(r3.getX() + " " + r3.getY() + " ");
System.out.println(r3.getWidth() + " " + r3.getHeight());
I have this code and I know that the output is 0 5 10 10 but i'm not entirely sure why. can anyone explain why?
public void modify(int newX, int y, int width, int h) {
int x = newX; // the value isn't saved to the class members
this.y = y; // this is saved, hence you see the change in the y value
width = width; // meaningless, the variable is overwritten with it's own value
this.height = height; // who is height? the function receives h
}
You have created a new object of type "int" for X within the modify method. This means that it only exists within that method since you're not passing it by reference. So, the newX value is only 5 within the modify method, but does not exist as '5' outside of it. this.y works fine because you've called that specific instance of the object and modified it's value. Therefore, it's retained outside the method. 'width = width' doesn't work because you're simply assigning 50=50 (since you've inputted 50 as the width). 'this.height = h' would be fine, but you've said 'this.height = height'. But, from the code you've given, 'height' doesn't exist.
y is the only instance variable that is actually modified in the modify method. The other the arguments passed in have no net effect on the state of the object.
Actually, the code shouldn't compile. height isn't defined in your method call. Unless this is another property that you didn't include in your code snippet.
int x = newX creates a new int named x that you then do nothing with. That's why r3.getX() returns 0, since you never modified it.
this.y = y changes the value of the field y within the Rectangle class. This is why this change is shown in your output as 5.
width = width changes the method parameter named width to itself. It doesn't change the value, but it also doesn't set the field width within Rectangle. No change shown, original value of 10 prints.
If height is a field elsewhere, then it makes sense that r3.getHeight() wouldn't update the field, since the parameter in the method call is for h, not height. If not, then I don't know how the code compiles since height isn't mentioned anywhere.
The "int x = newX" line creates a variable "x" on the stack that exists only for the duration of the current method call.
"this.x" would refer to the "x" created by the classes constructor. Which is probably what "getX()" returns.
This code shows the difference between the function stack variable and object variable. For function modify, the four passing variables are on the stack. The line declares a stack variable x and set its value as newX. The second line uses the object variable this.y and set to passing variable y. The third line is to assign the width to its self on stack. The fourth line uses the object variable height and assign to its self. Once the program goes out of the scope of function modify, all its stack variables' value are whacked. So the result is 0 5 10 10 because only the second line which is not stack variable this.y retains its value after calling function modify.
I would venture to say your issue is in how you are assigning the new values of x, y, width and height to your rectangle object.
Assuming that your modify method is in the rectangle class your code currently looks like this (I added comments on the mistakes:
public void modify(int newX, int y, int width, int h) {
int x = newX; //you are declaring a new x here...not assigning newX to rectangle's x
this.y = y; //this is correct
width = width; //here you're just assigning the parameter width its current value
this.height = height; //here you are assigning the rectangles height value to itself
}
I would HIGHLY advise finding a naming convention and sticking with it as it would help tremendously here.
Try something like this:
public void modify(int x, int y, int w, int h) { //changed names of parameters
this.x = x; //removed the int type declaration and used this. prefix
this.y = y; //changed nothing
this.width = w; //adjusted for renamed parameter, used this. prefix
this.height = h; // adjusted for renamed parameter, again used this. prefix
}
As you can see, sticking to a convention makes the code less confusing and easier to read. This also allows you to see your mistakes more easily as they will usually stick out from your convention like a sore thumb. Don't worry it comes with practice.