【发布时间】:2012-02-23 10:14:33
【问题描述】:
我的代码生成 0-1 形式的随机数 3 次,我需要将它添加到变量中,以便它变成二进制数。所以,理论上,这将运行 3 次,可能会给我 101 ;
String storage = null;
int i = 0;
while (i < 3) {
int binny = this.giveMeBinary();
storage.concat(String.valueOf(binny));
i++;
}
int ans = Integer.parseInt(storage);
但是当我尝试运行它时,我收到 NullPointerException 存储错误。有没有办法将字符串“添加”到变量中?
giveMeBinary 方法只返回 0 或 1。
【问题讨论】:
-
还要注意
storage.concat(...)不会改变storage的值。你需要做storage = storage.concat(...)。 -
顺便说一句,如果您的目标是
ans而不是storage,您可以使用位运算轻松完成:while(i<3) {ans <<= 1; ans |= this.giveMeBinary();i++;}或whle(i<3) { ans |= this.giveMeBinary()<<i;i++;} -
ahhhhh 是的......我明白你的意思......它不会将新值存储到存储中。