2017-07-06 173 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要求 - *有沒有辦法做到這一點,而不需要檢查每個屬性?* –