02-方法(动手动脑)

1.生成指定数目随机整数

 程序设计思想:

   使用Scanner对象接收用户输入的整数n(表示生成随机数的数目),然后循环执行n次 调用Math.random()*10000 % 10001生成0 - 10000范围内随机数,转换为整型并输出。

 程序代码:

 1 import java.util.Scanner;
 2 
 3 public class Rand {
 4     public static void main(String[] args) {
 5         Scanner in = new Scanner(System.in);
 6         int n = in.nextInt();
 7         for(int i = 0;i < n;i++)
 8             System.out.println((int)(Math.random()*10000) % 10001);
 9     }
10 }

 执行结果:

 

2.方法重载


样例代码:

 1 //方法重载
 2 public class MethodOverload {
 3 
 4     public static void main(String[] args) {
 5         System.out.println("The square of integer 7 is " + square(7));
 6         System.out.println("\nThe square of double 7.5 is " + square(7.5));
 7     }
 8     
 9     public static int square(int x){
10         return x * x;
11     }
12     
13     public static double square(double y){
14         return y * y;
15     }
16 }

执行结果:

结果分析:

  程序对square方法进行了重载。程序调用square函数时,根据传递参数的类型不同,调用与其参数类型一致的函数。

  程序中7是int型,square(7)调用的是int square(int),得到int型结果

  程序中7.5是double型,square(7.5)调用的是double square(double),从而得到double型结果

 

posted @ 2017-10-12 18:31  ╄冷丶夜♂  阅读(130)  评论(0编辑  收藏  举报