-2

Theres probably a lot of things wrong with this code but I can probably handle the rest, I just need to know how to fix the error "incompatible types: possible lossy conversion from double to int"

public class assignment5_3
{
   public static void main(String[] args)
   {    
      //System.out.println("The falling distance is "+d+" when time is "+t);
      for (int t = 1; t < 10; t++)
      {
         double result = fallingDistance();
      }
   }
   public static int fallingDistance()
   {
      double g = 9.8;
      int t = 5; 
      double d = (1/2)*g*t*t;
      return(d);

   }
}
  • 2
    `d` is a `double`, but your method returns an `int`, change the return type of `fallingDistance` to `double` – Bentaye Nov 29 '19 at 19:23
  • 3
    Note that `(1/2)` is integer division, The result of this is `0`, not `0.5`. You probably meant to do double division, e.g. by doing `1.0 / 2.0`. And there isn't really a point in having those variables. Just do `return 1.0 / 2.0 * 9.8 * 5 * 5;` or better, have it as constant `private static final int FALLING_DISTANCE = ...;`. – Zabuzard Nov 29 '19 at 19:42
  • You probably intended to have the method accept a parameter `int t` and then call it like `fallingDistance(t);`. Otherwise it will just always use `5` as time, since that is what you hardcoded in the method. Also, try to avoid abbreviating variable names. Write them out, makes the code much clearer. `gravity` and `time` and `distance`. – Zabuzard Nov 29 '19 at 20:20

2 Answers2

2

Your return type of function fallingDistance() should be double.

public static double fallingDistance()
   {
      double g = 9.8;
      int t = 5; 
      double d = (1/2)*g*t*t;
      return(d);

   }
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15
0

The problem with your code is that it is expecting an integer value in return statement but you are return a double which is why it is throwing the error. Go through this link to understand this better.