新手笔记之方法调用的生成随机字符

方法这章很难!

生成随机字符

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);
	
	}}}



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