2017-07-06 67 views
-3

Cube类有两个构造函数,一个接受转换为多维数据集的树属性的三个参数,另一个不需要任何参数,因此会创建一个“空”多维数据集。我的问题是一个布尔方法如何检查立方体是否有效或空?有没有办法做到这一点,而不需要检查每个属性?如何检查对象是否为“空”?

class Application { 

    public static void main(String[] args) { 

     Cube c1 = new Cube(4, 3, 6); 
     Cube c2 = new Cube(); 

     System.out.println(isNotEmpty(c1)); 
     System.out.println(isNotEmpty(c2)); 
    } 

    public static boolean isNotEmpty(Cube cube) { 
     if (/*cube attributes are NOT empty*/) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public static class Cube { 
     private int height; 
     private int width; 
     private int depth; 

     public Cube() {} 

     public Cube(int height, int width, int depth) { 
      this.height = height; 
      this.width = width; 
      this.depth = depth; 
     } 

     public int getHeight() { return height; } 
     public int getWidth() { return width; } 
     public int getDepth() { return depth; } 
    } 
} 
+3

'宽度== 0 &&高度== 0 && depth == 0'? – MadProgrammer

+3

为什么isEmpty是Cube类的一种方法? –

+1

你是什么意思[空](https://stackoverflow.com/questions/44937316/how-do-i-check-if-a-object-is-empty)? –

回答

0

由于看来这一个Cube拥有唯一的国家是高度,宽度和深度,那么你实际上可以只使用null代表空Cube

把第一个没有立方体的立方体叫做立方体没什么意义。使用null作为标记可能是最有意义的。

+0

也许应该摆脱无用的构造函数 –

0

在构造函数中使用布尔标志isEmptyCube。在创建对象时,它会自动标记为空是否为空。

public static class Cube { 
     //... 
     private boolean isEmptyCube; 
     public Cube() {isEmptyCube = true;} 
     public Cube(int hight, int width, int depth) { 
      //... 
      isEmptyCube = false; 
     } 
     public isCubeEmpty() { return isEmptyCube;} 
0

要么改变你的int字段的一个(或多个)是一个Integer对象,或引入新的布尔字段isSet或摆脱你的空构造

1)。如果您使用的Integer对象你可以测试,看它是否是null地方 - 作为int原语为0

缺省值2)如果你有一个布尔字段,您可以在默认为false,它在你的正确的构造函数设置为true

0

这似乎是一个非常棘手的问题。起初,我们必须有任何标准:What is an empty object?。当我们有一些标准,甚至是单一的,我们必须检查它。

从原因,当我们所考虑的Cube c3 = new Cube(0, 0, 0)喜欢的是不是空的,所以,这里是方法之一:

public class CubeApplication { 

    public static void main(String[] args) { 

     Cube c1 = new Cube(4, 3, 6); 
     Cube c2 = new Cube(); 
     Cube c3 = new Cube(0, 0, 0); 

     System.out.println(c1.isEmpty()); 
     System.out.println(c2.isEmpty()); 
     System.out.println(c3.isEmpty()); 
    } 

    static class Cube { 

     private int hight; 
     private int width; 
     private int depth; 
     private boolean isEmpty; 

     public Cube() { 
      this.isEmpty = false; 
     } 

     public Cube(int hight, int width, int depth) { 
      this.hight = hight; 
      this.width = width; 
      this.depth = depth; 
      this.isEmpty = true; 
     } 

     public boolean isEmpty() { 
      return this.isEmpty; 
     } 

     public int getHight() { 
      return this.hight; 
     } 

     public int getWidth() { 
      return this.width; 
     } 

     public int getDepth() { 
      return this.depth; 
     } 
    } 
} 

OUTPUT:

true 
false 
true 
+0

'Cube c3 = new Cube(0,0,0);'? –

+0

它适合我。我不明白你的意思 –

+0

OP要求 - *有没有办法做到这一点,而不需要检查每个属性?* –