Reputation: 211
I'm trying to save some data into an array but unfortunately all the data is saving into array[0] while it shouldn't be like this normally.
int j = 0;
while ( j < data.length ) {
float unbin = binary(data[2*j+1])+binary(data[2*j]);
float[] bin = new float[] {unbin};
print(bin);
j = j + 2;
}
it wrote all the data in bin[0]
, what's wrong with my code ?
how could I write :
bin[j] = unbin ?
to save the data in in bin[0] while j = 0 and so on ?
here is the updated code :
int j = 0 ;
float[] bin1 = new float[(data.length/2)];
while (j < data.length ) {
if ( data[2*j+2] >= 0 ) {
String unhx =(binary(data[2*j+3])+binary(data[2*j+2])+binary(data[2*j+1])+binary(data[2*j]));
float unbin = ((float)unbinary(unhx)/100);
bin1[j/2] = unbin;
print(bin1[1]);
}
else if ( data[2*j+2] < 0 && data[2*j+3] < 0 ) {
data[2*j] = (byte)(-data[2*j]);
data[2*j+1] = (byte)(-data[2*j+1]);
String unhx =(binary(data[2*j+1])+binary(data[2*j]));
float unbin = ((-1)*(float)unbinary(unhx)/100);
bin1[j/2] = unbin;
print(bin1[1]);
}
j = j + 2;
}
Upvotes: 0
Views: 2359
Reputation: 305
Subsequent to Jon's answer, as well as defining the array outside of the loop, you only need to add 1 to J, but ensure that the condition is
while ((2*j) <= data.length) {
....
}
You're also going to get ArrayIndexOutOfBoundsExceptions thrown, because when j = data.length, 2*j = 2* data.length, which is bigger than your data array.
Upvotes: 1
Reputation: 39
First, You need to declare the bin array BEFORE the loop (so that it exist (remain in scope) after you leave the loop).
Second, when you declare the bin array, you need to specify the size of the array.
float bin[] = new float[10]; // Creates an array of floats with 10 slots. b[0] - b[9]
(You probably want the array to be the same size as the "data" array, so use data.length in place of "10")
Then in the loop you'd say
bin[j] = unbin;
Also, the way you are incrementing j (j = j+2
), it looks like you wish to write to b[0] b[2] b[4], etc. You skip b[1], b[2], b[3]. If this is your intention, be sure you allocate enough room for the bin array. (I think you mean to do j = j+1
);
Upvotes: 2
Reputation: 6357
Bin is scoped inside your loop. It is recreated each time with a single element e.g. {unbin}.
It would appear that you want to convert a binary item which is two bytes long into a float upon each iteration.
int j = 0;
float[] bin = new float[(data.length/2)];
while ( j < data.length ) {
float unbin = binary(data[2*j+1])+binary(data[2*j]);
bin[j/2] = unbin;
j += 2;
}
Upvotes: 2
Reputation: 1503649
You're creating a new array (of length 1) on each iteration. You need to create the array before the while loop:
float[] bin = new float[...];
while (...) {
...
bin[j] = unbin;
}
(It's unclear what the length should be here - I suspect you don't want to be multiplying j
by 2 and incrementing it by 2 each time.)
Upvotes: 7