Let's Go!
java中产生随机汉字(推荐)
上一篇 /
下一篇 2011-04-01 18:53:32
/ 个人分类:JAVA学习&编程相关
4e00-9fa5编码范围,这个范围里应该都是中文。。。
引用楼主 hyb2008dxy 的帖子:
java中如何产生一个随机的汉字,不用预存在数组的方式来做的话,有没有其他方法?
答:参考代码如下:
- Java code
//在0x4e00---0x9fa5之间产生一个随机的字符publicstaticchargetRandomChar()
{return(char)(0x4e00+(int)(Math.random()*(0x9fa5-0x4e00+1)));
}
方法二:
给LZ写了一个,不晓得要得不?
import java.util.Date;
import java.util.Random;
public class Chinese {
public String getChinese(long seed) throws Exception {
String str = null;
int highPos, lowPos;
seed = new Date().getTime();
Random random = new Random(seed);
highPos = (176 + Math.abs(random.nextInt(39)));
lowPos = 161 + Math.abs(random.nextInt(93));
byte[] b = new byte[2];
b[0] = (new Integer(highPos)).byteValue();
b[1] = (new Integer(lowPos)).byteValue();
str = new String(b, "GB2312");
return str;
}
public static String get300Chinese() throws Exception {
Chinese ch = new Chinese();
String str = "";
for (int i = 300; i > 0; i--) {
str = str + ch.getChinese(i);
}
System.out.println(str);
return str;
}
public static void main(String[] args) throws Exception {
get300Chinese();
}
}
方法三:
Java codepublicclassTest1 {publicstaticvoidmain(String[] args) {
RandomHan han=newRandomHan();
System.out.println(han.getRandomHan());
}
}classRandomHan {privateRandom ran=newRandom();privatefinalstaticintdelta=0x9fa5-0x4e00+1;publicchargetRandomHan() {return(char)(0x4e00+ran.nextInt(delta));
}
}
方法四:
import java.util.Date;
import java.util.Random;
public class Chinese {
public String getChinese(long seed) throws Exception {
String str = null;
int highPos, lowPos;
seed = new Date().getTime();
Random random = new Random(seed);
highPos = (176 + Math.abs(random.nextInt(39)));
lowPos = 161 + Math.abs(random.nextInt(93));
byte[] b = new byte[2];
b[0] = (new Integer(highPos)).byteValue();
b[1] = (new Integer(lowPos)).byteValue();
str = new String(b, "GB2312");
return str;
}
public static String get300Chinese() throws Exception {
Chinese ch = new Chinese();
String str = "";
for (int i = 300; i > 0; i--) {
str = str + ch.getChinese(i);
}
System.out.println(str);
return str;
}
public static void main(String[] args) throws Exception {
get300Chinese();
}
}
转自: http://topic.csdn.net/u/20080507/14/09d90a22-7f46-44ba-9484-d5ca3d3093a4.html
java 随机字母输出到txt文档
2007年03月15日 星期四 16:36
import java.io.FileWriter; public class create { public static void main(String[] args) { char s; char k[] = new char[1000]; double m; try{ for(int i=0;i<1000;i++){ m = Math.random()*26+97; s = (char)m; System.out.print(s); k[i] = s; } FileWriter FW = new FileWriter("c:/123.txt"); FW.write(k); FW.close(); } catch(Exception e){ } } }
|
收藏
举报
TAG: