動手動腦-2
阿新 • • 發佈:2018-10-14
pack package ble oid stat 計算 span nth ner
package 課後練習; import java.util.Scanner; import java.util.*; public class 動手動腦_隨機整數 { public static void main(String[]args) { System.out.println("請輸入你想產生的隨機數的個數:"); Scanner sc=new Scanner(System.in); int y=sc.nextInt(); for(int i=0;i<y;i++) { int x=(int)(Math.random()*1000)+1; System.out.println(x); } } }
這個程序中運用了方法Math.random();用來產生1-1000的整數,可以自己定義要產生的整數的個數。
package 課後練習; public class 動手動腦_觀察代碼 { 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; } }
這個程序,特殊之處是兩個方法運用了相同的方法名,都是square,然後雖然方法名一樣,但是最後的結果是不一樣的,分別是用整數7計算而得和用浮點數7.5計算而得,說明方法重載如果參數類型或者參數個數不同時或參數類型順序不同時,函數可以根據不同的參數類型和參數個數進行計算。
查看JDK中的System.out.println()方法發現System.out.println()方法中實參表內可輸入很多類型。
動手動腦-2