動手動腦問題
阿新 • • 發佈:2017-10-12
得到 ner ble ima sta println int() new 隨機數
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型結果
動手動腦問題