1. 程式人生 > 其它 >Java中數學函式,自定義方法與呼叫

Java中數學函式,自定義方法與呼叫

2.1 數學函式 函式在Java當中也成為方法

2.1數學函式

函式在Java當中也成為方法

//得到一個隨機數
double value = Math.random();
System.out println(value);

Math是Java提供的類,用於提供數學計算的,random就是方法。Math.random()方法用於返回一個隨機數,隨機數範圍為0.0<=Math.random<1.0.

Java當中型別轉化的語法

int nValue = (int)value;

我們如果想要得到0~9之間的隨機數,還要乘10

int nValue = (int) (value*10);

例子:產生6位隨機數(驗證碼)

int code = (int
)((value*1000000);

注意:有時會有五位產生,因為有可能random隨機結果是0.012345555666,此時可以把Math.random的結果加上1

int code = (int)((value+1)*100000);

2.2自定義方法

main方法

// 固定的方法格式,main方法用於啟動程式
public static void main(String[] args){

}

方法的語法

// public(公共的) static(靜態) void(空型別)
public static void 方法名稱(方法引數){
  程式碼塊
}

駝峰式命名

每個單詞的首字母變成大寫,如使用者名稱稱UserName,我的文件MyDocument,密碼Password。

小駝峰

方法名遵守的是小駝峰,第一個單詞是小寫的

// 密碼
public static void password(){
  //程式碼塊
}
// 我的文件
public static void myDocument(){
  //程式碼塊
}

2.3自定義方法呼叫

newLine方法如何被呼叫呢,其實很簡單

public class Custom {

  public static void main(String[] args){

      System.out.println("測試");
      // 這裡執行一下 newLine 這個自定義方法的呼叫
      newLine();
      System.out.println(
"結束"); } public static void newLine(){ System.out.println(""); } }

注意順序,一定是先定義方法,後呼叫方法

實際上方法也可以被多次呼叫,newLine方法裡可以呼叫其他方法

public class Custom {

  public static void main(String[] args){
    System.out.println("測試");
    newLine();
    newLine();
    System.out.println("結束");
  }

  public static void newLine(){
    System.out.println("");
    // 呼叫下面的 format 方法
    format();
  }
  //格式化輸出內容,這裡只是為了測試方法的呼叫
  public static void format(){
    System.out.println("------------");
  }

}

現在我們來思考一下,為什麼需要方法呢?

1.解決程式碼複用的問題:比如說newLine方法不需要重複編寫這個邏輯

2.隱藏程式細節,這樣程式更加清晰,從而降低複雜度

下面我們來改一下產生驗證碼的程式,用方法實現:

 1 public class Custom {
 2 
 3   public static void main(String[] args) {
 4     random();
 5   }
 6 
 7   /**
 8   *生成6位隨機數
 9   */
10   public static void random(){
11     int code = (int) ((Math.random()+1) * 100000);
12     System.out.println(code);
13   }
14 
15 }