I have a Boolean
array and I am trying to make a corresponding char array, so that to each true in the new array corresponds a 1 and for each false a 0. this is my code but it seems the new array is empty, because nothing prints, the Boolean nums[]
prints fine.
char[] digits = new char[n];
for (int i = 0; i < n; i++) {
if (nums[i]) {
digits[i] = 1;
}
else if (!nums[i]) {
digits[i] = 0;
}
}
for (int k = 0; k < n; k++) {
System.out.print (digits[k]);
}
A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.
An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays.
Now, use the toCharArray() method to convert string to char array. char[] ch = str. toCharArray();
Your problem is that you don't have quotes surrounding the 1
and 0
.
for (int i = 0; i < n; i++) {
if (nums[i]) {
digits[i] = '1';
}
else {
digits[i] = '0';
}
}
Without the quotes, they are cast from int
s to char
s. 0 is actually the null character (NUL
), and 1 is start of heading or something like that. Java chars are encoded using UTF-16 (they're 16 bits long). The characters '0' and '1' are actually encoded by 48 and 49 respectively (in decimal).
EDIT: Actually, don't look at the ASCII table, look at the Unicode character set. Unicode is really a superset of ASCII, but it'll probably be more useful than the ascii table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With