Skip to content

Instantly share code, notes, and snippets.

@ExpDev07
Last active January 28, 2018 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ExpDev07/c4d728ed6a591b6ca5b5b176002e700a to your computer and use it in GitHub Desktop.
Save ExpDev07/c4d728ed6a591b6ca5b5b176002e700a to your computer and use it in GitHub Desktop.
Generates a random last name using Namey and Java
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Project created by ExpDev
*/
public class RandomNameExample {
private static final String USER_AGENT = "Mozilla/5.0";
/**
* Executed when program is ran
*
* @param args Additional arguments
* @throws Exception If name can't be retrieved
*/
public static void main(String[] args) throws Exception {
// Initiate main class
RandomNameExample nameExample = new RandomNameExample();
// My minecraft name
String mcName = "ExpDev";
System.out.println("Hello there " + mcName + ". I will now try and get you a cool last name!");
// Try and get a random last name for me
try {
// My random generated last name
String lastname = nameExample.getRandomLastname(Frequency.ALL);
System.out.println("Woop woop, the US Census Bureau database has decided that " + lastname + " would be a cool last name for you.");
System.out.println("Welcome to the server, " + mcName + " " + lastname + ". Hope you have fun!");
} catch (Exception e) {
System.out.println("Could not fetch a random last name for you: " + e.getMessage() + ".");
}
}
/**
* Generates a random last name based on the US Census Bureau database for names
*
* @return A random last name
* @throws Exception If name can't be retrieved or connection to API fails
*/
private String getRandomLastname(Frequency frequency) throws Exception {
String url = "http://namey.muffinlabs.com/name.json?count=1&type=surname&frequency=" + frequency.name();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
// Read stream
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Parse the json array returned
JsonArray array = new Gson().fromJson(response.toString(), JsonArray.class);
// Return the last name
return array.get(0).getAsString();
}
/**
* Frequency for a random name call
*/
public enum Frequency {
ALL,
COMMON,
RARE
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment