Could someone help understand these lines of code?
int[] byteCountArray = new int[256];
try (FileInputStream fileInputStream = new FileInputStream(fileName)) {
while (fileInputStream.available() > 0) {
byteCountArray[fileInputStream.read()] += 1;
}
So in the first line, the "byteCountArray" is created. The while loop then fills this array with the bytes from the file. But what are we adding the +1 to? The index? Why?
Thank you!
Comprehension question
Resolved
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Lisa
31 July 2021, 07:24
If a textfile is read, then a byte is in correlation with a character (ascii code).
If you now use the ascii code as index in an array and increment the corresponding value in the array for each occurrence of this byte, then you have a counter array for all characters in the file
0
Ryan Palmer
31 July 2021, 12:01
Thanks Lisa. A further question, if we are adding 1, however, with each byte, how will there ever be more than one occurrence?
0
Lisa
31 July 2021, 12:47
Take ABBA as example. An InputStream (contrary to a Reader) will not interprete the saved values as chars but read the plain byte (ascii) values and that's 65 66 66 65. Your code then will do the following:
byteCountArray[65]++;
byteCountArray[66]++;
byteCountArray[66]++;
byteCountArray[65]++;
All other array indices stay at zero while index 65 and 66 increased to 2. Now you could get your ascii table, look up which character belongs to which index and know how many times each character is present in the dataset.
+1
Ryan Palmer
31 July 2021, 16:55
Ok. I think I am starting to get it, but let me check.
If I have:
byteCountArray[fileInputStream.read()] += 1;
And say the "fileInputStream.read()" has taken the plain byte 65. This would mean that 65 would become the index, and the "1" would be the element?
The array would look like this:
(Indices) 62 63 64 65 66 67 68
(elements) [ ] [ ] [ ] [1] [ ] [ ] [ ]
Then if the loop came across another 65, it would go back to that same index and add 1?
Seems pretty clear now (if that is correct). Thanks for taking the time!
+1
Lisa
31 July 2021, 17:07solution
bull's eye
yeah, yeah :))
good luck 🤪
+2