Java 将一个盒子装入另一个盒子的程序

Java 将一个盒子装入另一个盒子的程序,java,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 >

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

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在他的回答中指出的那样,您尝试将
int
Box
对象的实例进行比较。关系比较器
需要两个
int
char
,而不是
对象

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

b.getLongestSide();
b1.getShortestSide();
而且,稍微精确一点,您在方法的其他部分的日志是不正确的,您不确定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.
}
一种更优雅(更面向对象)的方法是在
对象中创建一个方法
布尔框#fitsIn(框)

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;
    }
}
公共类框
{
整数长度=0;
整数宽度=0;
整数高度=0;
// ...
公共布尔fitsIn(@Nonnull final Box otherBox)
{
回来
长度
您得到的错误是什么?请检查此
b.length>b1
,这是无效的。另外,您应该将属性声明为private,并使用getter和setter。
b.length>b1
应该是
b.length>b1.length
b.getLongestSide();b1.getshortestide();这两条语句是无用的,您应该有类似int longside=b.getLongestSide()的内容;