I have code that generates a random number form 0-1 3 times and I need it to be added to a variable so it turns into a binary number.So, in theory, this would run three times and possibly give me 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);
But when I try and run this I get the NullPointerException error for storage. Is there a way to just "add" a string to the variable?
the method giveMeBinary just returns a 0 or a 1.
storage.concat(...)will not change the value of storage. You need to dostorage = storage.concat(...).ansand notstorage, you can do this easily with bit arithmetic:while(i<3) {ans <<= 1; ans |= this.giveMeBinary();i++;}orwhle(i<3) { ans |= this.giveMeBinary()<<i;i++;}