Skip to content

Instantly share code, notes, and snippets.

@apetz
Last active June 21, 2017 16:22
Show Gist options
  • Save apetz/83235a093bfddc63607b44a184fc6cf2 to your computer and use it in GitHub Desktop.
Save apetz/83235a093bfddc63607b44a184fc6cf2 to your computer and use it in GitHub Desktop.
Tony's answer to the SF Offline Programming Challenge "Hello World" problem
import java.util.regex.Pattern;
/**
* A (very) simple program that takes one optional command-line argument <name>
* and prints "Hello, <name>!" to STDOUT
*
* If no command line argument is provided, the program prints "Hello, world!" instead
*
* Can be compiled run using the following:
* $ javac HelloWorld.java
* $ jar cf HelloWorld.jar HelloWorld.class
* $ java HelloWorld "Stellan Skarsgård"
*
* Notes: the minimalist unicode-friendly name-matching regex is from
* https://stackoverflow.com/questions/15805555/java-regex-to-validate-full-name-allow-only-spaces-and-letters
*/
public class HelloWorld {
public static void main(String[] args) {
final String name = args.length > 0 ? args[0] : "world";
// verify command line arguments
if (args.length > 1) {
throw new IllegalArgumentException("Please provide only one name, enclose multi-word names in quotes");
}
// validate the name to make sure there is no unsafe characters, this is probably overkill
final Pattern nameValidator = Pattern.compile("^[\\p{L} .'-]+$");
if (!nameValidator.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid characters found in provided name");
}
System.out.print(String.format("Hello, %s!\n", name));
}
}
@egrim
Copy link

egrim commented Jun 21, 2017

General greeting output

Hello, world!

Targeted greeting output

  • java HelloWorld
Hello, world!
  • java HelloWorld "Stellan Skarsgård"
Hello, Stellan Skarsgård!

Bonus output

  • java HelloWorld too many cooks
Exception in thread "main" java.lang.IllegalArgumentException: Please provide only one name, enclose multi-word names in quotes
	at HelloWorld.main(HelloWorld.java:24)
  • java HelloWorld "mr. Comma,man"
Exception in thread "main" java.lang.IllegalArgumentException: Invalid characters found in provided name
	at HelloWorld.main(HelloWorld.java:29)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment