9.22
public class MethodOverload {
public static void main(String[] args) {
System.out.println("The square of integer 7 is " + square(7));
System.out.println("\nThe 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;
}
}
这里用了重载,方法名相同,但是参数类型不同
利用生成随机数的数学公式,编写方法生成指定数目的随机数
import java.util.ArrayList;
import java.util.List;
public class RandomNumberGenerator {
public static void main(String[] args) {
int count = 1000; // 指定生成随机数的数目,1000可以换成其他
long seed = System.currentTimeMillis(); // 使用时间作为种子
int a = 1103515245;
int c = 12345;
int m = 2147483648; // 2^31,int 范围
List<Integer> randomNumbers = generateRandomNumbers(count, seed, a, c, m);//get方法接受参数,使用循环生成随机数,然后添加到list中
for (int randomNumber : randomNumbers) {
System.out.println(randomNumber);
}
}
public static List<Integer> generateRandomNumbers(int count, long seed, int a, int c, int m) {
List<Integer> randomNumbers = new ArrayList<>();
long x = seed;
for (int i = 0; i < count; i++) {
x = (a * x + c) % m;
randomNumbers.add((int) x);
}
return randomNumbers;
}
}


浙公网安备 33010602011771号