2

For an assignment we are suppose to modify a custom BitString class. There are over 10 functions we need to actually write the code for and I am stuck on the very first one. This is the beginning parts to the class along with some of the methods contained that I am trying to use:

public class BitString implements Cloneable {
    // An array to hold the bits that make up the bit string.
    private boolean bits[];
    /**
     * A constant that defines the size of the default bit string.
     */
    public static final int DEFAULT_SIZE = 8;

    /**
     * Creates a new, all false, bit string of the given size.
     */
    public BitString(int size) {
        if (size < 1) throw new IllegalArgumentException("Size must be positive");
        bits = new boolean[size];
    }

    /**
     * Creates a new all false bit string of size DEFAULT_SIZE.
     */
     public BitString() {
         this(DEFAULT_SIZE);
     }

     /**
      * Set the value of a bit string at the given index to true.
      */
     public void set(int index) {
         bits[index] = true;
     }

     /**
      * Set the value of a bit string at the given index to false.
      */
     public void clear(int index) {
         bits[index] = false;
     }

Below is the method I am working on (The only part that was given is the method and the input types) I can not call bits.set() or bits.clear() or the same operations that they are doing. When compiling I get

Error: Cannot make a static reference to the non-static field bits

on both method calls.

public static BitString decimalToUnsigned(int n, int size) {
    //throw new UnsupportedOperationException("This function needs to be completed!");
    int result = 0;
    int multiplier = 1;
    int base = 2;

    while(n > 0) {
        int remainder = n % base;
        n = n / base;
        if (remainder == 0) {
            //value = false;
            try {
                //bits.clear(size);
                bits[size] = false;
            } catch (InsufficientNumberOfBitsException ie) {}
        } else {
            //value = true;
            try {
                //bits.set(size);
                bits[size] = true;
            } catch (InsufficientNumberOfBitsException ie) {}
        }
        result = result + remainder * multiplier;
        multiplier = multiplier * 10;
        size--;
    }

    System.out.println("Result..." + result);

    return(bits);
} 

Thanks for any help.

mdewitt
  • 2,526
  • 19
  • 23
user3845574
  • 41
  • 1
  • 1
  • 7
  • 2
    Did you mean to make the `decimalToUnsigned()` method static? I'm also not sure exactly what your question is. Do you need to get past the compile error or is something else wrong? – mdewitt Sep 18 '14 at 00:17
  • Try looking at this answer to help you understand why you can't access non-static fields from static methods if that is your question: http://stackoverflow.com/questions/8101585/cannot-make-a-static-reference-to-the-non-static-field – mdewitt Sep 18 '14 at 00:26
  • @mdewitt that decimalToUnsigned method was given to us as static, along with a lot of other methods we are suppose to finish like successor and twosComplement. I need to get past the compilation error so I can continue – user3845574 Sep 18 '14 at 00:53

2 Answers2

1

We're having to make some assumptions here: the static method is a method on BitString, for instance.

Given that, the method is evidently supposed to create a BitString object, since it returns one. So it should create one of the size you need for the parameters you are dealing with. Since you have the (arbitrary, somewhat silly) restriction of not being allowed to call the set and clear methods, you will need to access the bits variable from within the BitString that you create directly; since the static method is on the BitString class, you can do this:

public static BitString decimalToUnsigned(int n, int size)
{
  // ...
  BitString bitString = new BitString(size);
  // ... loops, logic, etc. all to be put in here; when you're ready to
  // access the bits array, use:
  bitString.bits[index] = false;
  // ...
  // then when you're ready to return your BitString object, just:
  return bitString;
}

Yes, bits is declared private, but that just means it cannot be accessed from outside the class. The static method is within the class, though it cannot use the member variables since the static method does not operate on an instance (other than one it creates).

See if that can get you through the compilation error and on to your logic.

p.s. I don't think this is a very good assignment; it will get your head around static vs. non-static methods, but I think there are better ways to do that. And saying that you have to use and return a class but you cannot call its methods is hardly a real-world scenario.

arcy
  • 12,845
  • 12
  • 58
  • 103
0

In your static method you need an instance of a BitString to put your vales in. This is how I would do it:

public class BitString implements Cloneable {

  /** A constant that defines the size of the default bit string. */
  public static final int DEFAULT_SIZE = 8;

  // an array to hold the bits that make up the bit string
  private boolean bits[];

  /** Creates a new, all false, bit string of the given size. */
  public BitString(int size) {
    if (size < 1) {
      throw new IllegalArgumentException("size must be positive");
    }
    bits = new boolean[size];
  }

  /** Creates a new all false bit string of size DEFAULT_SIZE. */
  public BitString() {
    this(DEFAULT_SIZE);
  }

  /** Set the value of a bit string at the given index to true. */
  public void set(int index) { // might want to check index bounds
    bits[index] = true;
  }

  /** Set the value of a bit string at the given index to false. */
  public void clear(int index) { // might want to check index bounds
    bits[index] = false;
  }

  public String toString() { // one possible implementation, might not want to add leading 0's
    StringBuilder buf = new StringBuilder(bits.length);
    for (Boolean bit : bits) {
      buf.append(bit ? '1' : '0');
    }
    return buf.toString();
  }

  public static BitString decimalToUnsigned(int n, int size) {
    // throw new UnsupportedOperationException("this function needs to be completed");
    // might want to check that size is big enough

    // this is the key here: you need an instance of the object that has the bits array inside it
    BitString result = new BitString(size);
    while (n != 0 && size > 0) {
      size--; // use size to index into the BitString
      if ((n & 1) == 1) { // % 2 doesn't work well with negative numbers, you have to worry about +-1 then
        result.set(size); // set bit if needed
      }
      n = n >>> 1; // unsigned shift to the next bit
    }
    return result;
  }

  public static void main(String[] args) {
    // can be invoked with just decimalToUnsigned(42, 10) but I want to make it more clear
    BitString example1 = BitString.decimalToUnsigned(42, 10);
    System.out.println(example1);

    BitString example2 = BitString.decimalToUnsigned(-42, 10); // will treat -42 as unsigned
    System.out.println(example2);

    BitString example3 = BitString.decimalToUnsigned(-1, 33); // will treat -1 as unsigned giving 32 1's
    System.out.println(example3);
  }
}

It prints:

0000101010
1111010110
011111111111111111111111111111111

nmore
  • 2,474
  • 1
  • 14
  • 21
  • I think this is likely a good answer to the question (though I haven't checked the logic), but it calls `set()`, and the OP said s/he was not allowed to do that. – arcy Sep 18 '14 at 16:36
  • @arcy I wonder if OP really can't use these methods, or if s/he doesn't know how/where to invoke them. After all, it would only take one line of code to do what those methods are doing, so it's not like it is a huge deal if the teacher/professor allowed them to use those methods. Seems like a completely unnecessary restriction to me, and actually hinders learning about how objects work. – nmore Sep 18 '14 at 16:45
  • I absolutely agree with you that it is an unnecessary restriction, and that it hinders learning about OO. I hadn't considered that it was part of the OP's lack of understanding, that's a good point. I thought it was something given as part of the assignment. In either event, your answer illustrates how it could be done without that restriction, and so is valuable. – arcy Sep 18 '14 at 16:48