Java中数学函数,自定义方法与调用

时间:2021-08-10
本文章向大家介绍Java中数学函数,自定义方法与调用,主要包括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 }

原文地址:https://www.cnblogs.com/anaxiansen/p/15123330.html