java在for循环之后跳过了我的一些代码

yuvru6vn  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(349)

我试图得到两个集合的并集,但是由于某些原因,我的代码没有错误,但是我得到并集的方法跳过了一些代码

  1. public Set union(Set s){
  2. Set union = new Set(count+s.count);
  3. for(int x=0;x<count;x++)
  4. union.set[x] = set[x];
  5. for(int y=count;y<s.count;y++){
  6. union.set[y] = s.set[y];
  7. }
  8. return union;
  9. }

程序可以工作,但问题是在第一个循环之后,它跳过了方法中的其余代码。
下面是我的代码的其余部分,可能与这个问题有关

  1. public class Set implements InterfaceSet{
  2. private int set[];
  3. private int count;
  4. public Set(){
  5. set = new int[max];
  6. count = 0;
  7. }
  8. public Set(int size){
  9. set = new int[size];
  10. count = size;
  11. }
  12. private int found;
  13. public void add(int e){
  14. found = 0;
  15. if(count<10){
  16. for(int x: set){
  17. if(x==e){
  18. found=1;
  19. break;
  20. }
  21. }
  22. if(found==0){
  23. set[count] = e;
  24. count++;
  25. }
  26. }
  27. }
  28. public void display( ){
  29. for(int x=0;x < count; x++){
  30. System.out.println(set[x]);
  31. }
  32. }
ki1q1bka

ki1q1bka1#

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

  1. public Set union(Set s){
  2. Set union = new Set(count + s.count);
  3. for(int x = 0; x < count; x++)
  4. union.set[x] = set[x];
  5. // updated
  6. for(int y = 0; y < s.count; y++){
  7. union.set[count + y] = s.set[y];
  8. }
  9. return union;
  10. }
k3bvogb1

k3bvogb12#

当你到达第二个环路时, count 将等于第一组的大小,但您正在将其与第二组的大小进行比较。如果第一组与第二组大小相同或大于第二组,则条件 count < s.count 将为false,跳过循环。
对于插入和读取的位置,需要使用不同的索引变量:

  1. public Set union(Set s){
  2. Set union = new Set(count+s.count);
  3. int insertPoint = 0;
  4. for(int i=0; i<count; i++, insertPoint++) {
  5. union.set[insertPoint] = set[i];
  6. }
  7. for(int i=0; i<s.count; i++, insertPoint++) {
  8. union.set[insertPoint] = s.set[i];
  9. }
  10. return union;
  11. }

这也是通常的惯例 i , j , k ,用于索引变量,除非它们有特定的含义,所以我继续切换 x 以及 yi .

展开查看全部

相关问题