Pawelnr1
Pawelnr1

Reputation: 233

I can't use math methods in Java

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

Upvotes: 2

Views: 30656

Answers (4)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. First of all java.lang.* is already included, So u do NOT need to import it.

2. To access a method in Math class you can do the following...

- Access the static method using Class name and dot operator.

Math.abs(-10);

- Access the static method directly, then u need to import as below.

import static java.lang.Math.abs;

abs(-10);

Upvotes: 0

user8681
user8681

Reputation:

To use static methods without the class they are in, you have to import it statically. Change your code to either this:

import static java.lang.Math.*;
float distance = hypot(xdif, ydif);//somewhere in the code

or this:

import java.lang.Math;
float distance = Math.hypot(xdif, ydif);//somewhere in the code

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500504

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);

Upvotes: 21

Ilya
Ilya

Reputation: 29693

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

or

import static java.lang.Math.hypot;

Upvotes: 2

Related Questions