用java写一个随机生成地址的方法
时间: 2023-02-07 10:51:11 浏览: 171
基于java语言的随机点生成
在 Java 中,可以使用 java.util.Random 类来生成随机数。您可以使用此类来生成随机的街道地址。下面是一个示例方法,它使用了随机数来生成随机地址:
```
import java.util.Random;
public class AddressGenerator {
private static final String[] STREET_NAMES = { "Main Street", "Park Avenue", "Maple Street", "Fifth Avenue", "Elm Street" };
private static final String[] CITY_NAMES = { "New York", "Los Angeles", "Chicago", "Houston", "Phoenix" };
private static final String[] STATE_NAMES = { "NY", "CA", "IL", "TX", "AZ" };
private Random rand;
public AddressGenerator() {
rand = new Random();
}
public String generateAddress() {
String street = STREET_NAMES[rand.nextInt(STREET_NAMES.length)];
int houseNumber = rand.nextInt(1000) + 1;
String city = CITY_NAMES[rand.nextInt(CITY_NAMES.length)];
String state = STATE_NAMES[rand.nextInt(STATE_NAMES.length)];
int zipCode = rand.nextInt(90000) + 10000;
return houseNumber + " " + street + ", " + city + ", " + state + " " + zipCode;
}
}
```
使用此方法时,您可以调用 generateAddress() 方法,并将其结果存储在字符串中。这个方法将返回一个随机生成的地址。
例如:
```
AddressGenerator generator = new AddressGenerator();
String address = generator.generateAddress();
```
阅读全文