将一个盒子装进另一个盒子的程序

时间:2019-10-18 16:24:34

标签: java

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

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");
      }
    }
 }

1 个答案:

答案 0 :(得分:1)

我在这里看到多个问题。

正如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.
}

一种更优雅的方式(也更面向对象)是在boolean Box#fitsIn(Box)对象中创建方法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;
    }
}
相关问题