2017-03-09 149 views
0

我创建一个程序,使并修改整数设置Java返回对象

这里是我的代码:

public class IntSet{ 
    private final int MAXALLOWEDSETVALUE=2000; 
    private boolean [] data = new boolean[MAXALLOWEDSETVALUE+1]; 

    public IntSet(int... elts) { 
     for(int iteration = 0; iteration < elts.length; iteration++) { 
      if(elts[iteration] <= MAXALLOWEDSETVALUE) 
      data[elts[iteration]] = true; 
     } 
    } 

    public IntSet(IntSet source){ 
     System.arraycopy(source.data, 0, this.data, 0, MAXALLOWEDSETVALUE); 
    } 
    public void setTo(IntSet source){ 
     System.arraycopy(source.data, 0, this.data, 0, MAXALLOWEDSETVALUE); 
    } 
    public void insertElement(int element){ 
     data[element] = true; 
    } 
    public void deleteElement(int element){ 
     data[element] = false; 
} 
    public boolean hasElement(int element){ 
     if(data[element] == true) 
      return true; 
     else 
      return false; 
    } 

    public boolean equals(IntSet other){ 
     for(int iteration = 0; iteration < MAXALLOWEDSETVALUE; iteration++) { 
      if(data[iteration] == other.data[iteration]) { 

      } else { 
       return false; 
      } 
     } 
     return true; 
    } 

    public String toString() { 
     String output = "{"; 
     for(int iteration = 0; iteration < MAXALLOWEDSETVALUE; iteration++) { 
      if(data[iteration] == true) 
       output += (iteration + ", "); 
     } 
     output += "}"; 
     return output; 
    } 

我和我的减函数挣扎:减法器功能形成了一套新的这等于第一组,除了第二组中的任何元素被删除。我知道我需要返回一个对象,但我不知道如何去做。任何帮助表示赞赏。

public IntSet subtract(IntSet other) { 
     for(int iteration = 0; iteration < MAXALLOWEDSETVALUE; iteration++) { 
      if(data[iteration] == true && other.data[iteration] == true) { 
       other.data[iteration] = false; 
      } 
      if(data[iteration] == true && other.data[iteration] == false) { 
       other.data[iteration] = true; 
      } 
     } 
     System.arraycopy(other.data, 0, this.data, 0, MAXALLOWEDSETVALUE); 
    } 
    public int getUpperLimit(){ 
     return MAXALLOWEDSETVALUE; 
    } 

} 
+1

欢迎来到Stack Overflow!看起来你可能会问作业帮助。虽然我们本身没有任何问题,但请观察这些[应做和不应该](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),并相应地编辑您的问题。 (即使这不是作业,也请考虑建议。) –

+0

谢谢!我个人认为我没有违反任何规则或任何东西。但是,谢谢你的建议! – Coder117

+0

您是否试图存储一组整数?如果是这样,你打算在哪里存储它?您正在使用'boolean'数组。为什么? – anacron

回答

1

你减的方法可以实现这样的:

  1. 创建当前对象的副本。请拨打newSet
  2. 如果other集合包含元素,请将newSet元素设置为false,该元素实质上是从newSet中“移除”该元素。
  3. 退货newSet

的代码会是这样的:


public IntSet subtract(IntSet other) { 
    IntSet newSet = new IntSet (this); 
    for(int iteration = 0; iteration < MAXALLOWEDSETVALUE; iteration++) { 
     if(other.data[iteration]) { 
      newSet.data[iteration] = false; 
     } 
    } 
    return newSet; 
} 

希望这有助于!

+0

酷,所以我可以创建另一个对象,只是当我在那个功能?这真是太棒了 – Coder117

+0

@ T.Dog是的。你也可以修改你所在的同一个对象,并用'return this'完成。 – MrMister

+0

循环体可以简化为if(other.data [iteration]){newSet.data [iteration] = false; }' –