File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Cup is 1/2 full, or empty? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Cup is 1/2 full, or empty?" Watch "Cup is 1/2 full, or empty?" New topic
Author

Cup is 1/2 full, or empty?

Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Have just spent 2 frustrating hours debugging a bouncing ball program that wasn't behaving correctly.

It turned out it was because I had a formula that was something like
So if b is 2 and c is 8, a = ...

yes, that's right, 2.

Seriously, why is Java this stupid?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

It is not stupid. That is just how integer calculations work (also on a lot of other languages).


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4241
    
    7

That's just how integer arithmetic works. If you don't want it to work like that, don't use integers!
Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Well, a, b, and c were doubles.

Looking at it from a beginner's perspective, it's definitely a bit strange that 1/2 == 0.

I just checked in VB, and it returns 0.5 there, even if you explicitly define two variables as integers and divide one by the other.

+ the whole of mathematics since the dawn of civilization, 1/2 has always been... well, 1/2, not 0.

At least throw a compiler warning or something.
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

1/2 with integers always has been 0 since the beginning of computers. That is the way it's implemented in the hardware and there is also a variant for floating point calculation. And throwing a warning will not help. What would that warning be: Warning you're using integer to calculate stuff
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10916
    
  12

Luigi Plinge wrote: the whole of mathematics since the dawn of civilization, 1/2 has always been... well, 1/2, not 0.

ummm...I'm not sure you know your math history. The concept of fractions is a relatively new concept, as compared to some others. Think about it...when you were first learning how do divide, did you say that 7 / 3 = 2.333333...., or did you say it was 2 with a remainder of 1?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Cup is 1/2 full, or empty?
 
Similar Threads
JQuiz - Practice Questions for SCJP2 (10/19/2003)
JMS question
algorithm problem with recursion
Does this count?
Basic arithmetic problem.