新手筆記之方法調用的生成隨機字符

方法這章很難!

生成隨機字符

1、生成從0到65 535之間的一個隨機整數(注意:因爲0 <= Math.random() <1.0,必須給65 535上加1):
(int) (Math.random() * (65 535 + 1))
2、生成一個隨機小寫字母
小寫字母的統一碼是一串連續的整數,從小寫字母a的統一碼開始,然後是b、c……z的統一碼。a的統一碼是:(in) ‘a'
所以,(int)‘a’到(int)‘z’之間的隨機整數是:
(int) ((int)'a' + Math.random() * ((int) -(int)'a' + 1)
//生成隨機字符
import java.util.Scanner;

public class Study4{
	
	public static char getStudy4(char ch1,char ch2){
		return(char)(ch1 + Math.random() * (ch2 - ch1 + 1));
	}
	public static char getRandomLowerCaseLetter(){
		return getStudy4('a','z');
	}
	public static char getRandomUpperCaseLetter(){
		return getStudy4('A','Z');
	}
	public static char getRandomDigitCharacter(){
		return getStudy4('0','9');
	}
	public static char getStudy4(){
		return getStudy4('\u0000','\uFFFF');
	}
	
	//顯示175個隨機的大寫寫字母
public static void main(String[] args) {
	final int N = 175;
	final int C = 25;
	for (int i = 0;i < N;i++){
		char ch = Study4.getRandomUpperCaseLetter();//定義和調用這類方法時仍然要使用括號
		if((i + 1) % C == 0)
			System.out.println(ch);
		else
			System.out.print(ch);
	
	}}}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章