【问题标题】:Java skips some of my code after for loopJava 在 for 循环后跳过了我的一些代码
【发布时间】:2021-03-07 10:52:52
【问题描述】:

我正在尝试获取两个集合的并集,但由于某种原因,我的代码没有错误,但我获取并集的方法跳过了一些代码

    public Set union(Set s){
    Set union = new Set(count+s.count);

    for(int x=0;x<count;x++)
        union.set[x] = set[x];

    for(int y=count;y<s.count;y++){
        union.set[y] = s.set[y];
    }
    return union;
}

程序可以运行,但问题是在第一个循环之后它会跳过方法中的其余代码。

这是我可能与问题相关的其余代码

public class Set implements InterfaceSet{
private int set[];
private int count;

public Set(){
        set = new int[max];
        count = 0;
    }

public Set(int size){
    set = new int[size];
    count = size;
}

private int found;
public void add(int e){
    found = 0;
    if(count<10){
        for(int x: set){
            if(x==e){
                found=1;
                break;
            }
        }
        if(found==0){
            set[count] = e;
            count++;
        }
    }
}

public void display( ){
    for(int x=0;x < count; x++){
        System.out.println(set[x]);
    }
}

【问题讨论】:

    标签: java loops for-loop methods


    【解决方案1】:

    您的联合方法似乎不正确。 你能试试这个吗?

    public Set union(Set s){
        Set union = new Set(count + s.count);
    
        for(int x = 0; x < count; x++)
            union.set[x] = set[x];
    
        // updated
        for(int y = 0; y < s.count; y++){
            union.set[count + y] = s.set[y];
        }
    
        return union;
    }
    

    【讨论】:

      【解决方案2】:

      当您进入第二个循环时,count 将等于第一个集合的大小,但您将它与第二个集合的大小进行比较。如果第一组与第二组大小相同或大于第二组,则条件count &lt; s.count 将为假,跳过循环。

      您需要对插入位置和读取位置使用不同的索引变量:

      public Set union(Set s){
          Set union = new Set(count+s.count);
          int insertPoint = 0; 
          for(int i=0; i<count; i++, insertPoint++) {
              union.set[insertPoint] = set[i];
          }
      
          for(int i=0; i<s.count; i++, insertPoint++) {
              union.set[insertPoint] = s.set[i];
          }
          return union;
      }
      

      通常也习惯使用i、j、k 来索引变量,除非它们具有特定含义,所以我继续将x 和y 切换为i。

      【讨论】:

      • 感谢您的解释。这真的很有帮助。代码现在可以工作了:)))
      猜你喜欢
      • 2012-05-23
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多