【发布时间】: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