31.1k views
2 votes
Write a method that takes a Rectangle as a parameter, and changes the width so it becomes a square (i.e. the width is set to the value of the length) (java)

User Kaji
by
3.9k points

2 Answers

6 votes

Final answer:

The method 'makeSquare' takes a Rectangle object as an argument and sets its width to match its length, thus converting it into a square.

Step-by-step explanation:

The question asks for a method in Java that takes a Rectangle object as a parameter and modifies it so that its width becomes equal to its length, effectively turning it into a square. Here's a concise method that accomplishes this:

public void makeSquare(Rectangle rect) {
rect.width = rect.length;
}

Assuming that you have a class named Rectangle with the properties width and length, this method sets the width of the rectangle to its length, thereby transforming the rectangle into a square. Note that this method assumes that the Rectangle class has public or accessible fields or utilizes appropriate setters to modify its dimensions.

User Douglas M
by
4.7k points
4 votes

Answer:

Step-by-step explanation:

The following code is written in Java, it is a function/method that takes in the length and width of the Rectangle as parameters and then overwrites the width to match the length. Then it prints both the length and width.

public static void rectangleToSquare(int width, int length) {

width = length;

System.out.println("Width: " + width);

System.out.println("Length: " + length);

}

User Frank Monroe
by
4.8k points