Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't use math methods in Java

Tags:

java

android

math

I need to use "hypot" method in my Android game however eclipse says there is no such a method. Here is my code:

import java.lang.Math;//in the top of my file
float distance = hypot(xdif, ydif);//somewhere in the code
like image 789
Pawelnr1 Avatar asked Nov 19 '25 01:11

Pawelnr1


2 Answers

Firstly, you don't need to import types in java.lang at all. There's an implicit import java.lang.*; already. But importing a type just makes that type available by its simple name; it doesn't mean you can refer to the methods without specifying the type. You have three options:

  • Use a static import for each function you want:

    import static java.lang.Math.hypot;
    // etc
    
  • Use a wildcard static import:

    import static java.lang.Math.*;
    
  • Explicitly refer to the static method:

    // See note below
    float distance = Math.hypot(xdif, ydif);
    

Also note that hypot returns double, not float - so you either need to cast, or make distance a double:

// Either this...
double distance = hypot(xdif, ydif);

// Or this...
float distance = (float) hypot(xdif, ydif);
like image 87
Jon Skeet Avatar answered Nov 20 '25 16:11

Jon Skeet


double distance = Math.hypot(xdif, ydif);  

or

import static java.lang.Math.hypot;
like image 35
Ilya Avatar answered Nov 20 '25 16:11

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!