对于分配,我们假设修改自定义 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()
他们正在执行的相同操作。编译时我得到
错误:无法对非静态字段位进行静态引用
在两个方法调用上。
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);
}
谢谢你的帮助。