01-方法

1、

import java.util.Random;

public class RandomNumber {
public static void main(String[] args) {
for(int i = 0; i < 10; i++){
System.out.println(getRandomIndex(100));
}
}
private static int getRandomIndex(int nMaxInexNum){
int nIndex = 0;
if(nMaxInexNum <= 0){
System.out.println("nMaxInexNum is not correct. nMaxInexNum=" + nMaxInexNum);
}
Random ranNum = new Random();
int randomIndex_1 = (ranNum.nextInt() % nMaxInexNum + nMaxInexNum) % nMaxInexNum;
int randomIndex_2 = (ranNum.nextInt() % nMaxInexNum + nMaxInexNum) % nMaxInexNum;
int randomIndex_3 = (ranNum.nextInt() % nMaxInexNum + nMaxInexNum) % nMaxInexNum;
nIndex = (randomIndex_1 + randomIndex_2 + randomIndex_3) % nMaxInexNum;
return nIndex;
}
}

输出结果:

52
74
87
51
82
95
85
45
42
21

2、

public class MethodOverload {
public static void main(String[]args) {
System.out.println("The square of integer 7 is " + square(7));
System.out.println(" The square of double 7.5 is " + square(7.5));
}
public static int square(int x) {
return x*x;
}
public static double square(double y) {
return y * y;
}
}

输出结果:

The square of integer 7 is 49

The square of double 7.5 is 56.25

这里用到了方法重载,函数名一样,参数类型不一样。还有参数数量不一样也可以使方法重载,重载与返回类型没有关系。

原文地址:https://www.cnblogs.com/Clark-Shao/p/13777633.html