Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a char[] using data from a boolean array?

Tags:

java

arrays

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]);
}
like image 943
kalina199 Avatar asked May 03 '20 19:05

kalina199


People also ask

How do you create a boolean array?

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.

Can you make an array of boolean?

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.

How do you char an array?

Now, use the toCharArray() method to convert string to char array. char[] ch = str. toCharArray();


1 Answers

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 ints to chars. 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

like image 112
user Avatar answered Sep 28 '22 07:09

user