写一段随机生成姓名的Java代码
时间: 2023-12-10 16:40:14 浏览: 96
Java随机产生人名
5星 · 资源好评率100%
以下是一个简单的随机生成姓名的Java代码示例:
```java
import java.util.Random;
public class RandomNameGenerator {
private static final String[] FIRST_NAMES = {"John", "Emily", "Michael", "Sophia", "William", "Jessica"};
private static final String[] LAST_NAMES = {"Smith", "Johnson", "Brown", "Lee", "Jones", "Davis"};
public static void main(String[] args) {
String firstName = getRandomElement(FIRST_NAMES);
String lastName = getRandomElement(LAST_NAMES);
System.out.println("Random name: " + firstName + " " + lastName);
}
private static String getRandomElement(String[] array) {
Random rand = new Random();
int index = rand.nextInt(array.length);
return array[index];
}
}
```
这个代码会在 `FIRST_NAMES` 和 `LAST_NAMES` 数组中随机选择一个名字和姓氏,并将它们组合成一个完整的名字。你可以根据需要修改数组来添加或删除名称。
阅读全文