一个将一个盒子放入另一个盒子的程序



这个程序应该确定一个盒子是否可以放入另一个盒子。我的代码有什么问题?当我编译它时,它给了我错误。

public class Box {
int length = 0;
int width = 0;
int height = 0;

public int getLongestSide() {
int max = length;
if(width > max) {
max = width;
}
if(height > max) {
max = height;
}
return max;
}
public int getShortestSide() {
int max = length;
if(width > max) {
max = width;
}
if(height > max) {
max = height;
}

这是主类。我在想也许我应该在主类中写一个 if 语句来比较盒子的侧面,以确定哪个适合另一个。请帮忙。

import java.util.Scanner;
public class apples {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Box b = new Box();
Box b1 = new Box();
b.length = input.nextInt();
b.width = input.nextInt();
b.height = input.nextInt();
b1.length = input.nextInt();
b1.width = input.nextInt();
b1.height = input.nextInt();
b.getLongestSide();
b1.getShortestSide();
if(b.length > b1 && b.width > b1.width && b.height > b1.height) {
System.out.println("b1 will fit in b");
}else {
System.out.println("b will fit in b1");
}
}
}

我在这里看到了多个问题。

正如 Villat 在他的回答中指出的那样,您尝试将intBox对象的实例进行比较。关系比较器>期望两个intchar,而不是一个Object

这些语句是无用的,因为您不使用输出:

b.getLongestSide();
b1.getShortestSide();

而且,只是一点精度,您在方法的 else 部分中的登录不正确,您不确定 b 是否适合 b1。 可以肯定的是,你应该做这样的事情:

if(b.length > b1 && b.width > b1.width && b.height > b1.height)
{
System.out.println("b1 will fit in b");
}
else if(b1.length > b.length && b.width > b1.width && b1.height > b.height)
{
System.out.println("b will fit in b1");
}
else
{
// Neither b fits in b1 nor b1 fits in b.
}

一种更优雅的方法(也是更面向对象(是在Box对象中创建boolean Box#fitsIn(Box)的方法。

public class Box 
{
int length = 0;
int width = 0;
int height = 0;
// ...
public boolean fitsIn(@Nonnull final Box otherBox)
{
return 
length < otherBox.length
&& width < otherBox.width 
&& height < otherBox.height;
}
}

最新更新