In java, how would I add a string to a string variable?
Solution 1
Your problem is that you are initializing the string to null. Doing something like so should solve your problem:
String storage = "";
int i = 0;
while (i < 3) {
int binny = this.giveMeBinary();
storage += (String.valueOf(binny));
i++;
}
int ans = Integer.parseInt(storage);
However, concatenating strings in such a manner is not recommended. What you can do is use a StringBuilder like so:
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());
Solution 2
You get the NullPointerException because you set the variable storage to null. You should start with
String storage = "";
Solution 3
If you want a binary number, i.e. a random number between 0 and 7 or 000 and 111 in binary.
int ans = giveMeBinary() * 4 + giveMeBinary() * 2 + giveMeBinary();
however if you want a decimal number which looks like a binary number.
int ans = giveMeBinary() * 100 + giveMeBinary() * 10 + giveMeBinary();
Solution 4
You have two problems:
You're never assigning a non-null value to
storage
, but you're calling theconcat
method on it. That will always throw aNullPointerException
You're assuming
String.concat
will modify the existing string value. It doesn't. Strings are immutable in Java.
I would suggest using a StringBuilder
instead, and calling append
in the loop:
int i = 0;
StringBuilder builder = new StringBuilder();
while (i < 3) {
int binny = this.giveMeBinary();
builder.append(binny);
i++;
}
int ans = Integer.parseInt(builder.toString());
Quite why you're then parsing a binary number such as "011" as if it were a decimal number is a different matter. What do you actually want the result to be? Do you really want the numbers 0, 1, 10, 11, 100, 101, 110 or 111?
Solution 5
If you want to use String concatenation then just initialise storage to "" (empty string) then use
storage += String.valueOf(binny);
but if you are looping and building Strings you should really use StringBuilder since Strings are immutable
StringBuilder buffer = new StringBuilder();
then
buffer.append(binny);
willkara
Updated on July 09, 2022Comments
-
willkara almost 2 years
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.