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.
Your problem is that you are initializing the string to null. Doing something like so should solve your problem:
However, concatenating strings in such a manner is not recommended. What you can do is use a StringBuilder like so: