*
The moose likes Beginning Java and the fly likes Why is the output  0.0? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why is the output  0.0?" Watch "Why is the output  0.0?" New topic
Author

Why is the output 0.0?

Brian Snyder
Ranch Hand

Joined: Feb 03, 2001
Posts: 142
I've been playing around with exception writing and extended an example to take an argument(int) from the command line, parseit, and feed it into a mthod for compuation. All works well except for the fact that I get 0.0 as the output.
Thanks in advance. Here's my code:
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
Hi, Brian.
The key line here is

Here's what happens:
1. Java interprets "d" and the return from doIt() as ints.
2. Therefore, the product of "d" and "doIt()" is an int.
3. Java interprets "1" as an int;
4. Java integer-divides 1 and the multiplication product, because each of the arguments to "/" is an int. (Integer-dividing means you divide and disregard any remainder.) So if your args[0] is 17, integer-dividing 1 by ( 4 * 17 ) yields 0. As another example, "7 / 2" in Java yields 3.
5. Java casts this integer (0) to a float, yielding the 0.0 you see.
The solution, here, Brian, is to fool Java into plain old dividing instead of integer dividing. Explicitly identifying "1" as a float to Java should do the trick:

When I run this code with an args[0] of 17, 0.014705882 is returned.
Hope this helps,
Art
Brian Snyder
Ranch Hand

Joined: Feb 03, 2001
Posts: 142
Thanks Art for that clear explaination.
I hope to return the favor someday.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why is the output 0.0?
 
Similar Threads
incompatible types: found double required float error;
doubts in 4 questions
Exception
no ArithmeticException??
:rolling: Innovative functions !!!