【问题标题】:Java methods in custom BitString class自定义 BitString 类中的 Java 方法
【发布时间】:2014-09-18 00:13:15
【问题描述】:

对于一个赋值,我们假设修改一个自定义的 BitString 类。我们需要实际编写代码的函数超过 10 个,而我被困在第一个函数上。这是该类的开始部分以及我尝试使用的一些方法:

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

下面是我正在处理的方法(给出的唯一部分是方法和输入类型)我不能调用bits.set()bits.clear() 或他们正在执行的相同操作。编译时我得到 ​​p>

错误:无法对非静态字段位进行静态引用

在两个方法调用上。

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

感谢您的帮助。

【问题讨论】:

  • 您的意思是让decimalToUnsigned() 方法静态化吗?我也不确定你的问题到底是什么。您需要克服编译错误还是有其他问题?
  • 如果您的问题是,请尝试查看此答案以帮助您了解为什么不能从静态方法访问非静态字段:stackoverflow.com/questions/8101585/…
  • @mdewitt,decimalToUnsigned 方法是作为静态方法提供给我们的,还有很多其他我们应该完成的方法,比如 successor 和 twosComplement。我需要克服编译错误才能继续

标签: java class methods bits bitstring


【解决方案1】:

我们必须在这里做出一些假设:例如,静态方法是 BitString 上的方法。

鉴于此,该方法显然应该创建一个 BitString 对象,因为它返回一个。因此,它应该为您正在处理的参数创建您需要的大小之一。由于您有不允许调用 set 和 clear 方法的(任意的,有些愚蠢的)限制,您将需要从您直接创建的 BitString 中访问 bits 变量;由于静态方法在 BitString 类上,您可以这样做:

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

是的,位被声明为私有的,但这只是意味着它不能从类外部访问。静态方法在类中,但它不能使用成员变量,因为静态方法不对实例(除了它创建的实例之外)进行操作。

看看这是否可以帮助您解决编译错误并进入您的逻辑。

附言我不认为这是一个很好的任务;它会让您了解静态与非静态方法,但我认为有更好的方法可以做到这一点。并且说你必须使用并返回一个类但你不能调用它的方法,这几乎不是现实世界的场景。

【讨论】:

    【解决方案2】:

    在您的静态方法中,您需要一个 BitString 的实例来放入您的 vales。我会这样做:

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

    打印出来:

    0000101010
    1111010110
    011111111111111111111111111111111

    【讨论】:

    • 我认为这可能是这个问题的一个很好的答案(虽然我没有检查逻辑),但它调用set(),并且 OP 说他/她不允许这样做.
    • @arcy 我想知道 OP 是否真的不能使用这些方法,或者她/他是否不知道如何/在哪里调用它们。毕竟,只需要一行代码就可以完成那些方法正在做的事情,所以如果老师/教授允许他们使用这些方法,这并不是什么大不了的事。对我来说似乎是一个完全不必要的限制,实际上阻碍了了解对象的工作原理。
    • 我完全同意你的观点,这是一个不必要的限制,它会阻碍学习 OO。我没有认为这是OP缺乏理解的一部分,这是一个很好的观点。我认为这是作为任务的一部分给出的。无论哪种情况,您的回答都说明了如何在没有这种限制的情况下完成,因此很有价值。
    猜你喜欢
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    相关资源
    最近更新 更多