2012-08-04 20 views
2

我需要在我的Android遊戲中使用「hypot」方法,但eclipse說沒有這樣的方法。這裏是我的代碼:我不能在Java中使用數學方法

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

回答

20

首先,你不需要在java.lang導入類型的。已經有一個隱含的import java.lang.*;。但是導入只需就可以通過它的簡單名稱來提供該類型;這並不意味着您可以在不指定類型的情況下引用方法。你有三個選擇:

  • 使用每個功能的靜態導入你想要的:

    import static java.lang.Math.hypot; 
    // etc 
    
  • 使用通配符靜態導入:

    import static java.lang.Math.*; 
    
  • 明確提及的靜態方法:

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

還要注意的是hypot回報double,不float - 讓你無論是需要轉換,或使distance一個double

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

// Or this... 
float distance = (float) hypot(xdif, ydif); 
2
double distance = Math.hypot(xdif, ydif); 

import static java.lang.Math.hypot; 
0

爲不使用他們在類的靜態方法,你必須輸入它靜態地。你的代碼更改爲這個:

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

或本:

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

首先java.lang中的*已經包含,所以你不需要將其導入。

2.要訪問在數學課上,你可以做以下的方法...

-訪問使用類名和點運算符靜態方法。

Math.abs(-10);

-訪問靜態方法直接,然後ü需要如下進口。

import static java.lang.Math.abs;

abs(-10);

相關問題