Scanner和Random使用
Scanner引用數(shù)據(jù)類型使用 :?
? ? 1.導(dǎo)包 : 指明要使用類型存在的位置
import 包名.類名;(權(quán)限定名)
package包信息的下面,class類型的上面
2.定義引用數(shù)據(jù)類型的變量|引用
引用數(shù)據(jù)類型 變量名|引用名 = new 引用數(shù)據(jù)類型();
3.使用功能
引用.功能名字();
Scanner : 接收用戶鍵盤輸入
1.導(dǎo)包? import java.util.Scanner;
2.創(chuàng)建Scanner類型的引用
Scanner sc = new Scanner(System.in);
3.使用功能
sc.nextByte();? ?接收用戶輸入的byte類型數(shù)據(jù)
sc.nextShort();? 接收用戶輸入的Short類型數(shù)據(jù)
sc.nextInt();? ? 接收用戶輸入的Int類型數(shù)據(jù)
sc.nextLong();? ?接收用戶輸入的Long類型數(shù)據(jù)
sc.nextFloat();? ?接收用戶輸入的Float類型數(shù)據(jù)
sc.nextDouble();? ?接收用戶輸入的Double類型數(shù)據(jù)
sc.next(); 接收用戶輸入的字符串?dāng)?shù)據(jù),從有效字符開始接收,遇到空格停止接收,直到遇到enter結(jié)束功能
sc.nextLine(); 接收用戶輸入的字符串?dāng)?shù)據(jù),接收任意字符,直到遇到enter結(jié)束
需要注意處理前面系列next功能遺留的enter問題
sc.close(); 應(yīng)該使用完畢進(jìn)行關(guān)閉
Random : 產(chǎn)生隨機(jī)數(shù)
1.導(dǎo)包? ?import java.util.Random;
2.創(chuàng)建Random類型的引用
Random ran = new Random();
3.使用功能
ran.nextInt();? ?產(chǎn)生int范圍內(nèi)的隨機(jī)整數(shù)
ran.nextInt(n);? ?產(chǎn)生[0,n)內(nèi)的隨機(jī)整數(shù)
ran.nextDouble()? 產(chǎn)生[0,1)之間的隨機(jī)小數(shù)
公式 :?
[0,n)? ? ran.nextInt(n)
[0,n]? ? ran.nextInt(n+1)
[min,max)? ran.nextInt(max-min)+min
過程 :?
ran.nextInt(max)? ?--> [0,max)
ran.nextInt(max)