This week's book giveaway is in the Spring forum.We're giving away four copies of Spring Boot in Practice and have Somnath Musib on-line!See this thread for details.
Win a copy of Spring Boot in Practice this week in the Spring forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Tim Cooke
• Ron McLeod
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Liutauras Vilda
• Henry Wong
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• Al Hobbs
• Carey Brown
Bartenders:
• Piet Souris
• Mikalai Zaikin
• Himai Minh

# Code Error

Greenhorn
Posts: 12
• Number of slices to send:
Optional 'thank-you' note:

Could anyone please point out the error in the code

for length =5
it gives checkbits= -6

Marshal
Posts: 76111
362
• Number of slices to send:
Optional 'thank-you' note:
Welcome to JavaRanch.

You realise that the Math.pow() method returns a double, and you might suffer rounding errors from that cast. It is worthwhile putting in some print statements both to print out the power and also the values of j as you traverse the loop. That should help you work out what is going on.

I can't tell just by reading the code, since I don't know what your loop is supposed to do.

Greenhorn
Posts: 7
• Number of slices to send:
Optional 'thank-you' note:
May be Problem with STATIC methode calling..ie(Math.pow())Check it..

Sheriff
Posts: 22665
127
• Number of slices to send:
Optional 'thank-you' note:
You are going backwards; j is going from 0 to -1 to -2 to ...
That means that Math.pow(2, j) will become smaller than 1 (but never smaller than 0) once j becomes smaller than 0, and the cast to int truncates it to 0. That means that the loop will break when length + 1 + j <= 0 which means when j == -6.

If you turn j-- into j++ the result is 4.

Ranch Hand
Posts: 101
• Number of slices to send:
Optional 'thank-you' note:
Hi,

I read your post for a few times now, however I still can figure out what do you mean by an error.
Perhaps you should share with us a desired result?!

Arpit Panwar wrote:

You have an infinitive loop for positive length in here.

Arpit Panwar wrote:

Luckily for you, you have a condition which breaks the loop.

In case j is -6, above condition would look like:
• length = 5 --> 5 + 1 - 6 = 0
• pow(2, -6) = 0,015625 --> ((int) 0,015625) => 0

• and since: 0 <= 0, the condition is fulfiled.

And the number -6 is the first one in a row, which breaks the loop.

I have to admit that this code snip looks very strange.
I'm still not sure if this was done intentionally or it is perhaps a side effect of a bad day. ;)

Regards,
Rok

 Don't get me started about those stupid light bulbs.
reply
Similar Threads