我有代码可以生成 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。
最佳答案
您的问题是您正在将字符串初始化为空。这样做应该可以解决您的问题:
String storage = "";
int i = 0;
while (i < 3) {
int binny = this.giveMeBinary();
storage += (String.valueOf(binny));
i++;
}
int ans = Integer.parseInt(storage);
但是,不建议以这种方式连接字符串。您可以做的是使用 StringBuilder像这样:
StringBuilder storage = new StringBuilder();
int i = 0;
while (i < 3) {
int binny = this.giveMeBinary();
storage.append(String.valueOf(binny));
i++;
}
int ans = Integer.parseInt(storage.toString());
关于java - 在java中,如何将字符串添加到字符串变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9083856/