Results 1 to 3 of 3
  1. #1
    footyvino's Avatar
    footyvino is offline Member
    Join Date
    Mar 2010
    Posts
    1
    Rep Power
    0

    Question Method won't return value

    Hi All,

    Yet another Java newbie here learning the basics. :D

    I can't figure out why this method 'fahrenheitToCelsius' won't return a double value. Can someone please help me?

    Java Code:
    public class TempConversion508 {
       public static void main(String[] args) {
          
          double test = fahrenheitToCelsius(120.0);
          System.out.println(test);
       }
       
       public static double fahrenheitToCelsius(double fahrenheit) {
    
          return (120.0 - 32.0) * (5 / 9);
       }
    }

    Output is: 0.0

    Thanks!

    Ash

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default

    Yup. 5 / 9 is integer division, which is rounded down.

    Either use at least one double value 5.0 / 9 or 5 / 9.0 or cast one of the ints to double
    Java Code:
    ((double) 5) / 9
    db

    db

  3. #3
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    5

    Default

    Quote Originally Posted by footyvino View Post
    Output is: 0.0
    the result is ok. if you devide two integer like you do ( 5 / 9 ) the result is an integer resp. 0, so your term become 0. to get a right result a quick solution is changing 5 or 9 to double 5.0 or 9.0 so that your term is (120.0 - 32.0) * (5 / 9.0). the result will now be automatically converted to an double so that the result of your term will be a double. an other solution is a explicit cast to double, like db explaine above.

    the automatic type promotion is a very important and basic concept in java. so i suggest to spend enough time to learn it.
    Last edited by j2me64; 03-26-2010 at 10:52 AM.

Similar Threads

  1. Return an object to use in another method
    By TidusSolan in forum New To Java
    Replies: 3
    Last Post: 03-19-2009, 08:00 PM
  2. method that return 2 arguments
    By itaipee in forum New To Java
    Replies: 19
    Last Post: 01-12-2009, 05:36 PM
  3. return a null method
    By valoyivd in forum New To Java
    Replies: 2
    Last Post: 04-21-2008, 11:19 PM
  4. Return question in a method.
    By MetalGear in forum New To Java
    Replies: 1
    Last Post: 01-13-2008, 04:45 AM
  5. Return value of method
    By cachi in forum New To Java
    Replies: 1
    Last Post: 08-01-2007, 08:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •