Building a bag class in Java

梦想与她 提交于 2019-12-13 06:00:20

问题


I'm in dire need of help with this project. I'm trying to implement a Bag class for a programming assignment, and I'm getting hung up on the addAll(), Union(), and equals(), methods.

Edit: According to the assignment, addAll() is supposed to add all of the the objects from the second array into the first. I'm no longer getting an error when I run it, but for some reason it will not add all of the elements from the second array, it will only add the first 2. Thanks guys, this one is working perfectly now!

Edit: For Union(), I'm supposed to create a third bag that will contain all the contents of the first 2 bags. I was getting an ArrayIndexOutOfBoundsException when running this method. I've updated the code following biddulph.r and it's also working great. Thanks again!

Edit: "First attempt" And for equals(), it's supposed to check the size of the bags to make sure they are equal in size, then check to see if they contain the same numbers. So as it's written now, my equals() method will compare sizes and return the boolean value for that, but I'm unsure of how to make it compare the actual values.

import java.util.Arrays;
import javax.swing.*;

public class bag {
  int maxSize = 10; //Size of the arrays
  int count = 0; //Number of items stored in the array
  int[] a;
  int[] b;
  bag c;
  bag d;

  public bag() {
    //for(int i = 0; i < maxSize; i++){
    //a[i] = (int)(1+Math.random()*100);
    //}
    a = new int[maxSize];
  }

  public String bagString() {
    return Arrays.toString(a);
  }

  public void add(int b) {
    try {
      a[count] = b;
      count++;
    } catch (ArrayIndexOutOfBoundsException n) {
      JOptionPane.showMessageDialog(null, "Array is full, element will not be added");
    }
  }

  public void removeRandom() {
    int i = (int)(1 + Math.random() * (count - 1));
    a[i] = a[count - 1];
    a[count - 1] = 0;
    count--;
  }

  public void remove(int b) {
    for (int i = 0; i < maxSize; i++) {
      if (contains(b)) {
        a[i] = a[count - 1];
      }
    }
  }

  public boolean isEmpty() {
    if (count == 0) return true;
    else return false;
  }

  public boolean contains(int b) {
    int tf = 0;
    for (int i = 0; i < maxSize; i++) {
      if (a[i] == b) tf = 1;
    }
    if (tf == 1) return true;
    else return false;
  }

  public int size() {
    return count;
  }

  public void addAll(bag c, bag d) {
    if (a.length >= c.size() + d.size()) {
      for (int i = 0; c.size() <= d.size(); i++) {
        c.add(d.a[i]);
      }
    }
  }

  public void union(bag c, bag d) {
    bag bigger = new bag();
    for (int i = 0; i < c.size(); i++) {
      bigger.add(c.a[i]);
    }
    for (int i = 0; count < d.size() - 1; i++) {
      bigger.add(d.a[i]);
    }
    System.out.println(bigger.bagString());
  }

      public boolean equals(bag c, bag d){

        if(c.size() != d.size()){

                return false;

        }else{

                for(int i = 0; i < c.union(c, d).size(); i++){

                        if(c.union(c, d).contains(c.a[i]) && c.union(c, d).contains(d.a[i])){

                        return true;                                   
                        }                              

                }              
                    return false;                              
        }

    }

}

I really appreciate any help you guys can give me, thanks.

EDIT: Thanks to everyone for your help, you guys are life savers.


回答1:


Your problem for addAll() is here

   if (a.length >= c.size() + d.size()) {

        for (int i = 0; c.size() <= d.size(); i++) {
            c.add(d.a[i]);
        }
   }

You shouldn't be adding elements until your c bag becomes bigger than d, you should be adding all of d's elements to c.

for (int i = 0; i < d.size(); i++) {
    c.add(d.a[i]);
}



回答2:


So the part of the assignment you are having issue with is:

public void addAll(bag c, bag d){
    if (a.length >= c.size() + d.size()) {

        for (int i = 0; c.size() <= d.size(); i++) {
            c.add(d.a[i]);
        }
    }
}

which you say is supposed to add all of the the objects from the second array into the first.

If you break that down and apply it to your addAll() method, it sounds like you are supposed to be adding all of the items in bag "d" into bag "c".

Your for loop is saying start i at 0, and add 1 to it until the size of c is less than or equal to d.

What it should be saying is start i at 0, and add 1 to it until you have gone through every item in d.

That would look like this:

for (int i = 0; i < d.size(); i++){
 c.add(d.a[i]);
} 

i is increased every time you go through the for loop, and i will stop increasing when you have got to the size of d (the second condition). At this point you will exit the for loop. You don't have to worry about the size of c.

In fact you can probably get rid of the if (a.length >= c.size() + d.size()) line as well.

I hope my explanation helps you understand why the changes have been made to the method.




回答3:


I think you have a lot of problems with the design of the class that you should address first. If you are representing the bag as a static or dynamic array then you only need one array, not 2. You also don't need two bags inside each bag as attributes, that doesn't make any sense; all you should have left is the size of the bag or count and the array to hold all the elements (which are integers in your case). Also, avoid naming parameters for functions and attributes for the class the same way. Not doing so might confuse the compiler and will require code like self.attributeName to use attributes; otherwise, the compiler assumes you're talking about the parameter.

If you make these changes, the rest should be straight-forward from here. Since it's an assignment, you should make these changes and try again because you won't learn if we provide the answers for you; you'll see it will be much easier once you structure it correctly.

P.S. it's a convention to start a class name with a capital letter. Bag and not bag




回答4:


addAll

There's a couple of problems with this function as written. First is that it's confusing to the caller. The code using this method would be something like this:

Bag bag1 = ...
Bag bag2 = ...
Bag bag3 = ...

bag1.addAll(bag2, bag3)

...or perhaps bag2.addAll(bag2, bag3). The function is intended to add elements from one bag in to another bag, so why does the caller have to specify three different bags? There's only two involved. You should either make the function static, so it can be called like Bag.addAll(bag1, bag2) or (better) make it totally clear who's getting elements added by making it take a single argument bag1.addAll(bag2).

Second problem is that the function isn't implemented correctly, but I think that's because you're getting confused because you've got three bags involved instead of two. To sketch out how it should be fixed:

Bag target = ...
Bag source = ...

if (target.a.length >= target.size() + source.size()) {
    for (int i = 0; i < source.a.length; i++) {
        target.add(source.a[i]);
    }
}

Good variable naming is your friend.

union

You haven't specified what problem you're having with your implementation, so I'm not going to simply rewrite it for you. Edit your question with the problem, and I'll help.

However, this is an excellent example of a method that should be static (a Factory method, in fact). It should be able ot be called like: Bag biggerBag = Bag.union(bag1, bag2).

EDIT after his comment regarding the .union problem

The problem with .union is that you're looping through each bag using some else's size. It boils down to, if you want add each element from source in to target, you should be only counting elements from source, as so:

bag bigger = new bag();
for (int i = 0; i <= c.size(); i++) {
  bigger.add(c.a[i]);
}    

note that your method does not protect against the bigger bag not being big enough. You should have a check to make sure that it is BEFORE the loops, or even better just create a big enough bag.

equals

Again, you need to show that you've tried to write it, and then ask a question specifying what you need help with. Update your question and I'll help.




回答5:


Your method:

public void addAll(bag c, bag d) {
    if (a.length >= c.size() + d.size()) {
        for (int i = 0; c.size() <= d.size(); i++) {
            c.add(d.a[i]);
        }
    }
}

betrays your lack of understanding of Object Oriented programming. Remember that the method addAll() is already acting on a bag, and so you should not need to specify 2 bags in the arguments.

Calling example:

mybag.addAll(yourBag); 

would demonstrate a possible usage - it would add all contents of yourBag into myBag.

I'll give you this method for free (assuming that the array 'a' contains the contents of the bag - something I'm not sure about because your variable names aren't clear):

public void addAll(Bag otherBag) {
    for (int i : otherBag.a) {
        add(i);
    }
}

The above method will copy all contents of otherBag into this bag.

Another thing I noticed - you also have a b[] instance variable - what's that for? You also have 2 other bag instance variables. Not sure why.



来源:https://stackoverflow.com/questions/14651105/building-a-bag-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!