# 如何检查矩形是否适合放入另一个矩形内？

go评论128阅读模式

How to check if Rectangle will fit inside another rectangle?

# 问题

``````我正在尝试编写一个方法，该方法接受两个矩形参数，如果第一个矩形适应于第二个矩形内部，则返回true，否则返回false。

import java.awt.Rectangle;

public class Square {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle(0, 0, 100, 200);
Rectangle rect2 = new Rectangle(0, 0, 100, 200);
fitsInside(rect1, rect2);
}

public static boolean fitsInside(Rectangle rec1, Rectangle rec2) {
if (rec1.width < rec2.width && rec1.height < rec2.height) {
return true;
} else {
return false;
}
}
}

``````

I am trying to write a method that takes two rectangle parameters, and will return true if the first rectangle fits inside the second rectangle and false if it doesn't.

``````import java.awt.Rectangle;
public class Square {

public static void main (String[] args) {
Rectangle rect1 = new Rectangle(0,0,100,200);
Rectangle rect2 = new Rectangle(0,0,100,200);
fitsInside(rect1, rect2);
}

public static boolean fitsInside(Rectangle rec1, Rectangle rec2) {

if (rec1.width &lt; rec2.width &amp;&amp; rec1.height &lt; rec2.height) {
return true;
} else {
return false;
}
}
}
``````

When I compile and run this code it returns nothing. Why does this not work and how I could fix it?

# 答案1

Surround the line where you call `fitsInside` with `System.out.println(...)` and it will display the result you're computing.

# 答案2

``````System.out.println(fitsInside(rect1, rect2));
``````

The function `fitsInside` returns a boolean variable, but you are not using its return value. Since you haven't printed anything, you didn't get the result.

Printing the result will solve your problem:

``````System.out.println(fitsInside(rect1, rect2));

``````

• 本文由 发表于 2020年10月9日 00:07:26
• 转载请务必保留本文链接：https://go.coder-hub.com/64266452.html
• java

go 60

go 47

go 58

go 73