首页 > 解决方案 > Java 在 for 循环后跳过了我的一些代码

问题描述

我试图获得两组的联合,但由于某种原因,我的代码没有错误,但我获得联合的方法跳过了一些代码

    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]);
    }
}

标签: javaloopsfor-loopmethods

解决方案


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

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;
}

推荐阅读