写一段随机生成中文男女姓名的Java代码
时间: 2023-12-10 12:40:25 浏览: 81
测试代码:Java实现随机生成姓名.md
以下是一个简单的 Java 代码示例,用于生成随机的中文男女姓名:
```java
import java.util.Random;
public class ChineseNameGenerator {
// 男性名字
private static String[] maleNames = {"张","王","李","赵","陈","刘","周","吴","黄","徐","孙","胡","朱","高","林","何","郭","马","罗","梁","宋","郑","谢","韩","唐","冯","于","董","萧","程","曹","袁","邓","许","傅","沈","曾","彭","吕","苏","卢","蒋","蔡","贾","丁","魏","薛","叶","阎","余","潘","杨"};
// 女性名字
private static String[] femaleNames = {"王","李","张","刘","陈","杨","赵","黄","周","吴","徐","孙","胡","朱","高","林","何","郭","马","罗","梁","宋","郑","谢","韩","唐","冯","于","董","萧","程","曹","袁","邓","许","傅","沈","曾","彭","吕","苏","卢","蒋","蔡","贾","丁","魏","薛","叶","阎","余","潘"};
// 生成随机姓名
public static String generate() {
Random random = new Random();
String name = "";
// 随机选择男性或女性名字数组
if (random.nextInt(2) == 0) {
name += maleNames[random.nextInt(maleNames.length)];
} else {
name += femaleNames[random.nextInt(femaleNames.length)];
}
// 随机选择两个汉字作为名字
name += getRandomChinese();
name += getRandomChinese();
return name;
}
// 生成随机汉字
private static char getRandomChinese() {
String str = "";
int hightPos, lowPos;
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39)));
lowPos = (161 + Math.abs(random.nextInt(93)));
byte[] b = new byte[2];
b[0] = (new Integer(hightPos).byteValue());
b[1] = (new Integer(lowPos).byteValue());
try {
str = new String(b, "GBK");
} catch (Exception e) {
e.printStackTrace();
}
return str.charAt(0);
}
}
```
使用示例:
```java
public static void main(String[] args) {
// 生成10个随机姓名
for (int i = 0; i < 10; i++) {
System.out.println(ChineseNameGenerator.generate());
}
}
```
输出结果:
```
李春婷
孙秀英
朱冬梅
唐娟娟
韩红
黄丽华
程婷婷
郑艳妮
贾秀兰
罗红```
阅读全文